The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
perf(ci): use native timing splits with bounded integration concurrency (#45837)
yuneng-jiangf58c86f1d711
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex b22c2b4b7a9..bfca8310c0e 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -2747,33 +2747,6 @@ jobs:- store_test_results:path: test-results/provider-replay-harness- integration_timing_snapshot:- machine:- image: ubuntu-2204:2024.04.1- resource_class: medium- working_directory: ~/project- steps:- - checkout- - run:- name: Prepare optional integration timing snapshots- command: mkdir -p /tmp/integration-timings/{extensions,providers,mcp}- - restore_cache:- keys:- - integration-timings-v1-extensions-{{ .Branch }}-{{ .Revision }}- - integration-timings-v1-extensions-{{ .Branch }}-- - restore_cache:- keys:- - integration-timings-v1-providers-{{ .Branch }}-{{ .Revision }}- - integration-timings-v1-providers-{{ .Branch }}-- - restore_cache:- keys:- - integration-timings-v1-mcp-{{ .Branch }}-{{ .Revision }}- - integration-timings-v1-mcp-{{ .Branch }}-- - persist_to_workspace:- root: /tmp- paths:- - integration-timings-integration_contracts:parameters:suite:@@ -2796,15 +2769,6 @@ jobs:parallelism: << parameters.parallelism >>steps:- setup_litellm_test_deps- - when:- condition:- or:- - equal: [extensions, << parameters.suite >>]- - equal: [providers, << parameters.suite >>]- - equal: [mcp, << parameters.suite >>]- steps:- - attach_workspace:- at: /tmp- when:condition:equal: [browser, << parameters.suite >>]@@ -2850,24 +2814,26 @@ jobs:test -z "$(docker ps -aq --filter name=postgres-db --filter name=redis-cache)"- when:condition:- or:- - equal: [extensions, << parameters.suite >>]- - equal: [providers, << parameters.suite >>]- - equal: [mcp, << parameters.suite >>]+ not:+ equal: [1, << parameters.parallelism >>]steps:- run:name: Prepare this shard's execution recordcommand: |- mkdir -p "/tmp/integration-shards/<< parameters.suite >>/$CIRCLE_NODE_INDEX"- cp test-results/integration-<< parameters.suite >>/execution.json "/tmp/integration-shards/<< parameters.suite >>/$CIRCLE_NODE_INDEX/execution.json"+ results="test-results/integration-<< parameters.suite >>"+ if [ "<< parameters.mode >>" = replica ]; then+ results="$results-replica"+ fi+ mkdir -p "/tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >>/$CIRCLE_NODE_INDEX"+ cp "$results/execution.json" "/tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >>/$CIRCLE_NODE_INDEX/execution.json"if [ "<< parameters.suite >>" = mcp ]; then- mkdir -p "/tmp/integration-shards/mcp/$CIRCLE_NODE_INDEX/coverage"- cp test-results/integration-mcp/coverage/data "/tmp/integration-shards/mcp/$CIRCLE_NODE_INDEX/coverage/data.$CIRCLE_NODE_INDEX"+ mkdir -p "/tmp/integration-shards/mcp-standard/$CIRCLE_NODE_INDEX/coverage"+ cp test-results/integration-mcp/coverage/data "/tmp/integration-shards/mcp-standard/$CIRCLE_NODE_INDEX/coverage/data.$CIRCLE_NODE_INDEX"fi- persist_to_workspace:root: /tmp/integration-shardspaths:- - << parameters.suite >>+ - << parameters.suite >>-<< parameters.mode >>- store_test_results:path: test-results- store_artifacts:@@ -2877,7 +2843,11 @@ jobs:parameters:suite:type: enum- enum: [extensions, providers, mcp]+ enum: [management, accounting, database, extensions, providers, mcp]+ mode:+ type: enum+ enum: [standard, replica]+ default: standardshards:type: integermachine:@@ -2891,12 +2861,8 @@ jobs:- run:name: Verify every << parameters.suite >> case ran exactly oncecommand: |- .venv/bin/python -m tests.integration._support.sharding /tmp/integration-shards/<< parameters.suite >> \- --shards << parameters.shards >> --timings-output /tmp/integration-timings/<< parameters.suite >>/timings.json- - save_cache:- key: integration-timings-v1-<< parameters.suite >>-{{ .Branch }}-{{ .Revision }}- paths:- - /tmp/integration-timings/<< parameters.suite >>+ .venv/bin/python -m tests.integration._support.sharding /tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >> \+ --shards << parameters.shards >>- when:condition:equal: [mcp, << parameters.suite >>]@@ -2906,7 +2872,7 @@ jobs:command: |mkdir -p test-results/integration-mcp/coverageexport COVERAGE_FILE="$PWD/test-results/integration-mcp/coverage/data"- .venv/bin/python -m coverage combine --rcfile=tests/integration/mcp_coverage.toml /tmp/integration-shards/mcp/*/coverage+ .venv/bin/python -m coverage combine --rcfile=tests/integration/mcp_coverage.toml /tmp/integration-shards/mcp-standard/*/coverage.venv/bin/python -m coverage report --rcfile=tests/integration/mcp_coverage.toml > test-results/integration-mcp/coverage/coverage.txt.venv/bin/python -m coverage html --rcfile=tests/integration/mcp_coverage.toml -d test-results/integration-mcp/coverage/html- store_artifacts:@@ -3205,48 +3171,59 @@ workflows:- not:equal: ["", << pipeline.parameters.routing_parity_base >>]jobs:- - integration_timing_snapshot:- name: integration-timing-snapshot- integration_contracts:name: integration-<< matrix.suite >>matrix:parameters:suite: [sdk, cost, browser]+ parallelism: 1- integration_contracts:name: integration-securitysuite: security+ parallelism: 1resource_class: xlarge- integration_contracts:name: integration-managementsuite: management- parallelism: 8+ parallelism: 4+ - integration_shard_coverage:+ name: integration-management-coverage+ suite: management+ shards: 4+ requires: [integration-management]- integration_contracts:name: integration-accountingsuite: accounting- parallelism: 8+ parallelism: 4+ - integration_shard_coverage:+ name: integration-accounting-coverage+ suite: accounting+ shards: 4+ requires: [integration-accounting]- integration_contracts:name: integration-providerssuite: providers- parallelism: 16- requires:- - integration-timing-snapshot+ parallelism: 8- integration_shard_coverage:name: integration-providers-coveragesuite: providers- shards: 16+ shards: 8requires:- integration-providers- integration_contracts:name: integration-databasesuite: databaseparallelism: 2+ - integration_shard_coverage:+ name: integration-database-coverage+ suite: database+ shards: 2+ requires: [integration-database]- integration_contracts:name: integration-mcpsuite: mcpresource_class: xlargeparallelism: 2- requires:- - integration-timing-snapshot- integration_shard_coverage:name: integration-mcp-coveragesuite: mcp@@ -3256,25 +3233,35 @@ workflows:- integration_contracts:name: integration-extensionssuite: extensions- parallelism: 32- requires:- - integration-timing-snapshot+ parallelism: 8- integration_shard_coverage:name: integration-extensions-coveragesuite: extensions- shards: 32+ shards: 8requires:- integration-extensions- integration_contracts:name: integration-management-replicasuite: managementmode: replica- parallelism: 8+ parallelism: 4+ - integration_shard_coverage:+ name: integration-management-replica-coverage+ suite: management+ mode: replica+ shards: 4+ requires: [integration-management-replica]- integration_contracts:name: integration-database-replicasuite: databasemode: replicaparallelism: 2+ - integration_shard_coverage:+ name: integration-database-replica-coverage+ suite: database+ mode: replica+ shards: 2+ requires: [integration-database-replica]- postgres_suite:name: proxy-behaviortest_path: tests/proxy_behaviordiff --git a/.circleci/scripts/run_integration.sh b/.circleci/scripts/run_integration.shindex 4bdef5eb23b..28d1fba68c7 100644--- a/.circleci/scripts/run_integration.sh+++ b/.circleci/scripts/run_integration.sh@@ -216,18 +216,11 @@ if [ "$suite" = browser ]; thenexit 0fi-node_files=()-case_shards=1-case_shard_index=0-if [ "$suite" = extensions ] || [ "$suite" = providers ] || [ "$suite" = mcp ]; then- case_shards="${CIRCLE_NODE_TOTAL:-1}"- case_shard_index="${CIRCLE_NODE_INDEX:-0}"-elif [ "${CIRCLE_NODE_TOTAL:-1}" -gt 1 ]; then- split="$(.venv/bin/python tests/integration/run.py "$suite" --list \- | circleci tests split --split-by=timings --timings-type=filename)"- read -r -a node_files <<< "$(printf '%s' "$split" | tr '\n' ' ')"- test "${#node_files[@]}" -gt 0- printf '%s\n' "${node_files[@]}" > "$results/node-files.txt"+shard_arguments=()+if [ "${CIRCLE_NODE_TOTAL:-1}" -gt 1 ]; then+ .venv/bin/python tests/integration/run.py "$suite" --list \+ | circleci tests split --split-by=timings --timings-type=filename > "$results/node-files.txt"+ shard_arguments=(--shard-files "$results/node-files.txt")fienv -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \@@ -240,13 +233,13 @@ env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \LITELLM_LICENSE="${LITELLM_LICENSE:-}" \INTEGRATION_SEED="$INTEGRATION_SEED" \INTEGRATION_ORDER_SEED="$INTEGRATION_ORDER_SEED" \- INTEGRATION_CASE_SHARDS="$case_shards" INTEGRATION_CASE_SHARD_INDEX="$case_shard_index" \+ INTEGRATION_CASE_SHARDS="${CIRCLE_NODE_TOTAL:-1}" INTEGRATION_CASE_SHARD_INDEX="${CIRCLE_NODE_INDEX:-0}" \LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 \INTEGRATION_PROXY_DATABASE_URL="$INTEGRATION_PROXY_DATABASE_URL" \INTEGRATION_PROXY_READ_REPLICA_URL="$INTEGRATION_PROXY_READ_REPLICA_URL" \INTEGRATION_ROUTING="$INTEGRATION_ROUTING" \.venv/bin/python tests/integration/run.py "$suite" --results "$results" \- --timings "/tmp/integration-timings/$suite/timings.json" "${node_files[@]}"+ "${shard_arguments[@]}"if [ "${INTEGRATION_COVERAGE:-0}" = 1 ]; thenfor covered_pid in "$proxy_pid" "$peer_pid"; dodiff --git a/tests/integration/README.md b/tests/integration/README.mdindex 8734e2e6237..3bbfc8e386e 100644--- a/tests/integration/README.md+++ b/tests/integration/README.md@@ -10,7 +10,15 @@ Use `tests/integration/run.py management`, `accounting`, `database`, `providers`Management also requires `INTEGRATION_PEER_URL`, `REDIS_HOST` and `REDIS_PORT`. CircleCI starts two directly addressed proxy processes sharing only that job's stores. The test-only CLI wrapper supplies enterprise route entitlement, following the existing behavior suite's convention. It does not qualify license validation; run it with one worker and no reload-The generated lifecycle models use 20 examples, eight steps, generation and shrinking, with isolated resources per example. HTTP operation caps include generation and shrinking and exempt cleanup. Local qualification defaults to seed 4106601 and canonical order; CircleCI derives exploration and ordering seeds from the checked-out revision and workflow ID. The ordering seed shuffles files, scoped fixture configurations and cases within each configuration. Cases sharing a module or class fixture parameter stay together, so shuffling does not repeatedly rebuild the same configuration. Case partitions also group tests using the same unparametrized module or class fixtures. These groups split when they exceed a node's estimated time budget, limiting repeated setup without placing an oversized group on one node. A successful shard census saves every case's setup, call and teardown duration. The next CircleCI run restores that shared snapshot and balances measured cost. Missing or invalid timing data falls back to equal case weights. New cases receive the median known cost, and stale case identities cannot select or omit tests. Use `--timings <path>` to reproduce a measured partition Use `--seed` and `--order-seed` to reproduce a run. Actual installed Hypothesis version, settings, seeds and collected order are written beside the execution manifest+The generated lifecycle models use 20 examples, eight steps, generation and shrinking, with isolated resources per example. HTTP operation caps include generation and shrinking and exempt cleanup. Local qualification defaults to seed 4106601 and canonical order; CircleCI derives exploration and ordering seeds from the checked-out revision and workflow ID. The ordering seed shuffles files, scoped fixture configurations and cases within each configuration. Cases sharing a module or class fixture parameter stay together, so shuffling does not repeatedly rebuild the same configuration++CircleCI uses its built-in `circleci tests split --split-by=timings --timings-type=filename` to assign test files using the uploaded JUnit timings. Each file stays on one node, preserving its module and parametrized fixtures. Jobs default to one node. Parallelism should use the smallest node count that keeps the complete job, including setup and cleanup, within twenty minutes. A group that already finishes within that target on one node stays on one node. Management, accounting and management replica currently use four nodes. Providers and extensions use eight nodes; database and MCP use two, and fast suites use one. No job is configured above eight nodes. A single slow file can still determine a suite's runtime; split such a file along independent fixture boundaries rather than adding more nodes++Every node collects the same candidate files before applying CircleCI's assigned file list. Its execution record retains the candidate inventory and the selected, passed and skipped cases. An empty assigned file list produces an empty shard, not a full-suite fallback. Every parallel group has a dependent census job that rejects an empty candidate inventory, missing shards, omitted cases and duplicate execution. Standard and replica runs keep separate workspace records++Future change-based selection belongs before timing splitting. Pass the selected group files or node IDs to `run.py <group> --list` to list their files, then give those filenames to CircleCI. Run the same candidate selection on every node with `--shard-files <CircleCI-output-path> --shards <count> --shard-index <index>`. The census compares execution with the candidate inventory, while full-suite runs remain the default. CircleCI determines scheduling from timing history; timing data never selects or omits candidates. Use `--seed` and `--order-seed` to reproduce test generation and order. The installed Hypothesis version, settings, seeds and collected order are recorded beside the execution manifest++A future selector must explicitly skip a group when no candidates apply; omitting positional candidates means the full group. Keep full runs on the default branch and scheduled workflows, and select the full affected groups when shared fixtures, CI configuration or an unknown dependency changesReuse the existing canned provider handlers through `_support/upstream.py`. It rejects internal request fields and exposes actual received requests for independent assertions. Register every created resource for cleanup immediately, keep expected values independent of production calculations, and assert readback plus the runtime effect of a change@@ -34,7 +42,7 @@ Accounting cases compare persisted input and output cost components against liteProvider contracts exercise actual TCP requests with synthetic credentials and local protocol peers. The S3 verifier uses independently implemented equations, a published known-answer vector, a fixed signing clock and deliberately invalid signed requests. Bedrock cases clear ambient AWS credential sources and check the literal model path, loaded role references, STS requests and bearer-only behavior-CircleCI runs providers on 16 parallel nodes, partitioning cases while keeping scoped fixture configurations together. Each node owns its services. The dependent providers coverage job verifies all 16 execution records against the full case inventory and rejects missing, duplicate, failed or incomplete execution. Use `--shards 16 --shard-index <index>` to reproduce a node locally+CircleCI runs providers on eight isolated nodes using its file timing splitter. Each node owns its services. The dependent providers coverage job verifies all eight execution records against the candidate case inventory and rejects missing, duplicate, failed or incomplete execution. The node's assigned filenames are saved in `node-files.txt` beside its execution recordStreaming checks send real HTTP transfer chunks, including one-byte partitions, fragmented tools, incomplete transfers and a cancellation barrier. They assert meaningful text, tool arguments, final usage and persisted cost. The Redis recovery case owns a separate database and Redis process, uses the supported one-second circuit-breaker recovery setting, waits for the real subscriber and verifies response data in Redis after restart. CircleCI reuses its existing Redis image for that extra process; it never pulls an image during tests@@ -42,7 +50,7 @@ The `messages_endpoint/` directory holds `/v1/messages` endpoint contracts: natiThe sdk shard exercises the SDK's own HTTP clients against local protocol peers with no gateway in the path, so a case here fails only when the client library or its wire behavior changes. The HTTP/2 case runs a hypercorn TLS peer offering h2 and http/1.1 over ALPN, drives the sync and async httpx handlers at it with `LITELLM_HTTP2` off and on, and asserts the version both the client and the peer observed on the wire. Put a test here only when it needs no proxy or database. CircleCI starts a local Redis for this shard like the others, so SDK-side caching cases that need a real Redis server belong here too; a case that reaches the gateway belongs in one of the other shards-The extensions shard uses the built-in generic callback and guardrail transports. It checks callback correlation and credential exclusion, guardrail rewriting and denial, retained OpenAI consumers and A2A wire versions. CircleCI runs it on 32 parallel large nodes. Each node starts its own database, Redis, upstream and proxy and runs its share of cases serially. The runner assigns cases deterministically by estimated duration, keeping scoped fixture configurations together. Each node records the full collection inventory and its selected, passed and skipped nodes. The dependent coverage job rejects missing shards, differing inventories, omitted or duplicate cases and incomplete execution. Use `--shards 32 --shard-index <index>` to reproduce a node locally. More parallel nodes increase setup overhead and concurrent machine use. Tests keep the isolation of a serial run; they still must not assume a particular set of sibling files. `run.py <group> --list` prints a group's files and `run.py <group> <file>...` runs a subset of them+The extensions shard uses the built-in generic callback and guardrail transports. It checks callback correlation and credential exclusion, guardrail rewriting and denial, retained OpenAI consumers and A2A wire versions. CircleCI runs it on eight parallel large nodes using its file timing splitter. Each node starts its own database, Redis, upstream and proxy and runs its assigned files serially. The dependent coverage job verifies all eight execution records against the candidate case inventory. Tests must not assume a particular set of sibling filesThe security shard uses four pytest workers on an xlarge machine, each with a private database and Redis. Route sweeps use a new HTTP client for every call and share only the TLS verification context, so authentication and response cookies cannot cross callers. The canary rig supplies owned OpenAI and Anthropic endpoints and synthetic credentials and rejects attempted external egressdiff --git a/tests/integration/_support/ordering.py b/tests/integration/_support/ordering.pyindex 7dbc85396ff..fc10c372a93 100644--- a/tests/integration/_support/ordering.py+++ b/tests/integration/_support/ordering.py@@ -2,39 +2,12 @@ from __future__ import annotationsfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclass-from functools import reducefrom itertools import chain, groupby-from math import ceil, isfinite-from statistics import medianfrom types import MappingProxyTypefrom typing import Finalimport pytestfrom _pytest.python import get_direct_param_fixture_func-from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, TypeAdapter, ValidationError--EMPTY_DURATIONS: Final[Mapping[str, float]] = MappingProxyType({})---class CaseTiming(BaseModel):- model_config = ConfigDict(frozen=True, strict=True)-- nodeid: str = Field(min_length=1)- seconds: FiniteFloat = Field(ge=0)---TIMINGS: Final = TypeAdapter(tuple[CaseTiming, ...])---def parse_timings(content: str) -> Mapping[str, float]:- try:- values: Final = TIMINGS.validate_json(content)- except ValidationError:- return EMPTY_DURATIONS- durations: Final = {value.nodeid: max(value.seconds, 0.001) for value in values}- if len(durations) != len(values) or not isfinite(sum(durations.values())):- return EMPTY_DURATIONS- return MappingProxyType(durations)@dataclass(frozen=True, slots=True)@@ -120,59 +93,3 @@ def _file_groups(cases: Iterable[CollectedCase]) -> tuple[tuple[str, str], ...]:def fixture_groups(cases: tuple[CollectedCase, ...]) -> Mapping[str, str]:files: Final = groupby(sorted(cases, key=_file), key=_file)return MappingProxyType(dict(chain.from_iterable(_file_groups(members) for _, members in files)))---def _allocate(- shards: tuple[tuple[str, ...], ...], group: tuple[str, ...], durations: Mapping[str, float]-) -> tuple[tuple[str, ...], ...]:- index: Final = min(- range(len(shards)),- key=lambda candidate: (sum(durations[nodeid] for nodeid in shards[candidate]), len(shards[candidate])),- )- return tuple((*shard, *group) if candidate == index else shard for candidate, shard in enumerate(shards))---def _add_case(- groups: tuple[tuple[str, ...], ...], case: CollectedCase, maximum: float, durations: Mapping[str, float]-) -> tuple[tuple[str, ...], ...]:- if not groups:- return ((case.nodeid,),)- if sum(durations[nodeid] for nodeid in groups[-1]) + durations[case.nodeid] > maximum:- return (*groups, (case.nodeid,))- return (*groups[:-1], (*groups[-1], case.nodeid))---def _partition_group(- cases: Iterable[CollectedCase], maximum: float, durations: Mapping[str, float]-) -> tuple[tuple[str, ...], ...]:- members: Final = tuple(sorted(cases, key=lambda case: case.nodeid))- nodeids: Final = tuple(case.nodeid for case in members)- if members[0].parameters:- return (nodeids,)- return reduce(lambda groups, case: _add_case(groups, case, maximum, durations), members, ())---def case_shards(- cases: tuple[CollectedCase, ...], count: int, durations: Mapping[str, float] = EMPTY_DURATIONS-) -> tuple[frozenset[str], ...]:- if count < 1:- raise ValueError("Integration shard count must be positive")- groups: Final = fixture_groups(cases)- known: Final = tuple(durations[case.nodeid] for case in cases if case.nodeid in durations)- default: Final = max(float(median(known)), 0.001) if known else 1.0- weights: Final = MappingProxyType({case.nodeid: max(durations.get(case.nodeid, default), 0.001) for case in cases})-- def key(case: CollectedCase) -> str:- return groups[case.nodeid] or case.nodeid-- maximum: Final = sum(weights.values()) / count if known else float(max(1, ceil(len(cases) / count)))- members: Final = tuple(- chain.from_iterable(- _partition_group(group, maximum, weights) for _, group in groupby(sorted(cases, key=key), key=key)- )- )- ordered: Final = tuple(sorted(members, key=lambda group: (-sum(weights[nodeid] for nodeid in group), group[0])))- allocation: Final = reduce(- lambda shards, group: _allocate(shards, group, weights), ordered, tuple(() for _ in range(count))- )- return tuple(frozenset(shard) for shard in allocation)diff --git a/tests/integration/_support/sharding.py b/tests/integration/_support/sharding.pyindex 5267985ad17..661b9626e17 100644--- a/tests/integration/_support/sharding.py+++ b/tests/integration/_support/sharding.py@@ -9,15 +9,12 @@ from typing import Finalfrom pydantic import BaseModel, ConfigDict, Field, ValidationError-from tests.integration._support.ordering import TIMINGS, CaseTiming-class ShardingOptions(BaseModel):model_config = ConfigDict(frozen=True)directory: Pathshards: int = Field(gt=0)- timings_output: Path | None = Noneclass ShardExecution(BaseModel):@@ -31,16 +28,6 @@ class ShardExecution(BaseModel):shard_index: intcomplete: boolexitstatus: int- timings: tuple[CaseTiming, ...] = ()---def merged_timings(executions: tuple[ShardExecution, ...]) -> tuple[CaseTiming, ...]:- timings: Final = tuple(chain.from_iterable(execution.timings for execution in executions))- measured: Final = Counter(timing.nodeid for timing in timings)- selected: Final = Counter(chain.from_iterable(execution.collected for execution in executions))- if measured != selected or any(amount != 1 for amount in measured.values()):- return ()- return tuple(sorted(timings, key=lambda timing: timing.nodeid))def shard_errors(executions: tuple[ShardExecution, ...], count: int) -> tuple[str, ...]:@@ -88,7 +75,6 @@ def main() -> int:parser: Final = argparse.ArgumentParser()parser.add_argument("directory", type=Path)parser.add_argument("--shards", required=True, type=int)- parser.add_argument("--timings-output", type=Path)options: Final = ShardingOptions.model_validate(vars(parser.parse_args()))paths: Final = tuple(sorted(options.directory.glob("*/execution.json")))try:@@ -100,9 +86,6 @@ def main() -> int:if errors:sys.stderr.write("\n".join(errors) + "\n")return 1- if options.timings_output is not None:- options.timings_output.parent.mkdir(parents=True, exist_ok=True)- options.timings_output.write_bytes(TIMINGS.dump_json(merged_timings(executions)))sys.stdout.write(f"Verified {len(executions[0].inventory)} integration cases across {options.shards} isolated shards\n")diff --git a/tests/integration/conftest.py b/tests/integration/conftest.pyindex abb4a94c880..280a828e1d4 100644--- a/tests/integration/conftest.py+++ b/tests/integration/conftest.py@@ -16,7 +16,7 @@ from redis import Redisfrom tests.integration._support.client import Gateway, eventually, gateway_from_environmentfrom tests.integration._support.generation import LIFECYCLE_SETTINGSfrom tests.integration._support.manifest import OWNED_DIRECTORIES-from tests.integration._support.ordering import CaseTiming, case_shards, collected_case, fixture_groups, parse_timings+from tests.integration._support.ordering import collected_case, fixture_groupsfrom tests.integration._support.provider import SharedProvider, shared_providerfrom tests.integration._support.routing import RoutingPluginfrom tests.integration.run import GITHUB_FILES@@ -25,7 +25,8 @@ COLLECTED: Final = pytest.StashKey[tuple[str, ...]]()INVENTORY: Final = pytest.StashKey[tuple[str, ...]]()REPORTS: Final = pytest.StashKey[list[pytest.TestReport]]()WORKER_INVENTORY: Final = TypeAdapter(tuple[str, ...])-TIMING_PATH: Final[TypeAdapter[Path | None]] = TypeAdapter(Path | None)+SHARD_PATH: Final[TypeAdapter[Path | None]] = TypeAdapter(Path | None)+SHARD_FILES: Final = pytest.StashKey[frozenset[str] | None]()INTEGER_OPTION: Final = TypeAdapter(int)@@ -48,13 +49,14 @@ def pytest_addoption(parser: pytest.Parser) -> None:parser.addoption("--integration-order-seed", type=int, default=0)parser.addoption("--integration-shard-count", type=int, default=1)parser.addoption("--integration-shard-index", type=int, default=0)- parser.addoption("--integration-timings", type=Path)+ parser.addoption("--integration-shard-files", type=Path)def pytest_configure(config: pytest.Config) -> None:config.addinivalue_line("markers", "integration: owned real-service integration contracts")config.addinivalue_line("markers", "covers(*ids): legacy contract IDs kept for existing tests, not enforced")config.stash[REPORTS] = []+ config.stash[SHARD_FILES] = _shard_files(SHARD_PATH.validate_python(config.getoption("integration_shard_files")))config.pluginmanager.register(IntegrationReportPlugin(config))if os.environ.get("INTEGRATION_ROUTING"):config.pluginmanager.register(RoutingPlugin(config))@@ -100,13 +102,16 @@ def _order_key(seed: int, nodeid: str, group: str = "") -> tuple[bytes, bytes, breturn _digest(seed, nodeid.split("::", 1)[0]), _digest(seed, group or nodeid), _digest(seed, nodeid)-def _timing_content(path: Path | None) -> str:+def _shard_files(path: Path | None) -> frozenset[str] | None:if path is None:- return "[]"+ return Nonetry:- return path.read_text()- except (OSError, UnicodeError):- return "[]"+ files: Final = tuple(path.read_text().splitlines())+ except (OSError, UnicodeError) as error:+ raise pytest.UsageError(f"Cannot read integration shard selection: {error}") from error+ if len(frozenset(files)) != len(files) or any(not file for file in files):+ raise pytest.UsageError("Integration shard selection contains duplicate or blank files")+ return frozenset(files)@pytest.hookimpl(wrapper=True)@@ -134,13 +139,15 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Itemindex: Final = INTEGER_OPTION.validate_python(config.getoption("integration_shard_index"))if count < 1 or not 0 <= index < count:raise pytest.UsageError("Integration shard index must be within the positive shard count")- if count > 1:- timing_path: Final = TIMING_PATH.validate_python(config.getoption("integration_timings"))- shards: Final = case_shards(- tuple(collected_case(item) for item in owned), count, parse_timings(_timing_content(timing_path))- )- selected: Final = tuple(item for item in items if item not in owned or item.nodeid in shards[index])- deselected: Final = tuple(item for item in owned if item.nodeid not in shards[index])+ files: Final = config.stash[SHARD_FILES]+ if count > 1 and files is None:+ raise pytest.UsageError("Parallel integration runs require CircleCI's shard file selection")+ if files is not None:+ available: Final = frozenset(item.nodeid.split("::", 1)[0] for item in owned)+ if files - available:+ raise pytest.UsageError(f"Integration shard selected uncollected files: {sorted(files - available)}")+ selected: Final = tuple(item for item in items if item not in owned or item.nodeid.split("::", 1)[0] in files)+ deselected: Final = tuple(item for item in owned if item.nodeid.split("::", 1)[0] not in files)config.hook.pytest_deselected(items=deselected)items[:] = selectedconfig.stash[COLLECTED] = tuple(item.nodeid for item in items if item in owned)@@ -154,15 +161,13 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:returncollected: Final = session.config.stash.get(COLLECTED, ())reports: Final = tuple(report for report in session.config.stash[REPORTS] if report.nodeid in collected)- timings: Final = tuple(- CaseTiming(nodeid=nodeid, seconds=sum(report.duration for report in reports if report.nodeid == nodeid))- for nodeid in collected- )+ inventory: Final = session.config.stash.get(INVENTORY, collected)+ empty_shard: Final = session.config.stash[SHARD_FILES] == frozenset() and bool(inventory)passed: Final = tuple(report.nodeid for report in reports if report.when == "call" and report.passed)skipped: Final = tuple(report.nodeid for report in reports if report.skipped)complete: Final = (- exitstatus == 0- and bool(collected)+ (exitstatus == 0 or (empty_shard and exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED))+ and (bool(collected) or empty_shard)and sorted(collected) == sorted(passed + skipped)and not any(report.failed for report in reports))@@ -172,14 +177,13 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:json.dumps({"collected": collected,- "inventory": session.config.stash.get(INVENTORY, collected),+ "inventory": inventory,"shard_count": session.config.getoption("integration_shard_count"),"shard_index": session.config.getoption("integration_shard_index"),"passed": passed,"skipped": skipped,- "timings": tuple({"nodeid": timing.nodeid, "seconds": timing.seconds} for timing in timings),"complete": complete,- "exitstatus": exitstatus,+ "exitstatus": 0 if complete else exitstatus,"hypothesis_version": version("hypothesis"),"hypothesis_seed": session.config.getoption("hypothesis_seed"),"order_seed": session.config.getoption("integration_order_seed"),@@ -196,6 +200,8 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:)if not complete and exitstatus == 0:session.exitstatus = pytest.ExitCode.TESTS_FAILED+ if complete and empty_shard:+ session.exitstatus = pytest.ExitCode.OK@pytest.fixturediff --git a/tests/integration/database/test_harness_lifecycle.py b/tests/integration/database/test_harness_lifecycle.pyindex 63e3cba7363..91688eef263 100644--- a/tests/integration/database/test_harness_lifecycle.py+++ b/tests/integration/database/test_harness_lifecycle.py@@ -16,6 +16,7 @@ from contextlib import AbstractContextManager, ExitStackfrom pathlib import Pathfrom queue import SimpleQueuefrom threading import Event+from tempfile import TemporaryDirectoryfrom types import FrameTypefrom typing import Final, Literal@@ -38,6 +39,7 @@ from tests.integration._support.database_relay import (held_statement_relay,)from tests.integration._support.runtime import configure_executor+from tests.integration._support.sharding import ShardExecution, shard_errorsclass ExitRecord(TypedDict):@@ -282,75 +284,173 @@ def test_seeded_collection_reuses_scoped_fixtures_and_executes_every_case(tmp_pa)-def test_partitioned_collection_reuses_unparametrized_fixtures_and_executes_every_case(tmp_path: Path) -> None:[email protected]("workers", (1, 2))[email protected]("subset", (False, True))+def test_native_file_selection_reuses_fixtures_and_qualifies_an_empty_shard(+ tmp_path: Path, workers: int, subset: bool+) -> None:events: Final = tmp_path / "events.txt"- probe: Final = tmp_path / "test_fixture_probe.py"- probe.write_text(- "import pytest\nfrom pathlib import Path\n"- f"EVENTS = Path({str(events)!r})\n"- "def record(value):\n"- " with EVENTS.open('a') as output:\n"- " output.write(value + '\\n')\n"- "@pytest.fixture(scope='module')\n"- "def shared():\n"- " record('start shared')\n"- " yield 'shared'\n"- " record('stop shared')\n"- "@pytest.mark.parametrize('number', range(4))\n"- "def test_shared(shared, number):\n"- " assert shared == 'shared'\n"- " record('shared ' + str(number))\n"- "@pytest.mark.parametrize('number', range(8))\n"- "def test_plain(number):\n"- " record('plain ' + str(number))\n"+ root: Final = Path(__file__).resolve().parents[3]+ with TemporaryDirectory(prefix="native-selection-", dir=Path(__file__).parent) as directory:+ probe: Final = Path(directory) / "test_fixture_probe.py"+ plain: Final = Path(directory) / "test_plain_probe.py"+ probe.write_text(+ "import pytest\nfrom pathlib import Path\n"+ f"EVENTS = Path({str(events)!r})\n"+ "def record(value):\n"+ " with EVENTS.open('a') as output:\n"+ " output.write(value + '\\n')\n"+ "@pytest.fixture(scope='module')\n"+ "def shared():\n"+ " record('start shared')\n"+ " yield 'shared'\n"+ " record('stop shared')\n"+ "@pytest.mark.parametrize('number', range(4))\n"+ "@pytest.mark.xdist_group('shared')\n"+ "def test_shared(shared, number):\n"+ " assert shared == 'shared'\n"+ " record('shared ' + str(number))\n"+ )+ plain.write_text(+ "import pytest\nfrom pathlib import Path\n"+ f"EVENTS = Path({str(events)!r})\n"+ "@pytest.mark.parametrize('number', range(8))\n"+ "def test_plain(number):\n"+ " with EVENTS.open('a') as output:\n"+ " output.write('plain ' + str(number) + '\\n')\n"+ "def test_existing_skip():\n"+ " pytest.skip('retained skip identity')\n"+ )+ selections: Final = (str(probe.relative_to(root)), str(plain.relative_to(root)), "")+ candidates: Final = (+ (f"{selections[0]}::test_shared[1]", f"{selections[1]}::test_existing_skip") if subset else selections[:2]+ )+ listed: Final = subprocess.run(+ (sys.executable, "-P", "tests/integration/run.py", "database", "--list", *candidates),+ cwd=root,+ capture_output=True,+ text=True,+ timeout=15,+ check=False,+ )+ assert listed.returncode == 0, listed.stdout + listed.stderr+ assert tuple(listed.stdout.splitlines()) == tuple(sorted(selections[:2]))+ outputs: Final = tuple(tmp_path / str(index) for index in range(3))+ files: Final = tuple(tmp_path / f"selection-{index}.txt" for index in range(3))+ for selection, path in zip(selections, files, strict=True):+ path.write_text(selection + "\n" if selection else "")+ results: Final = tuple(+ subprocess.run(+ (+ sys.executable,+ "-P",+ "-m",+ "pytest",+ *candidates,+ "--noconftest",+ "-p",+ "tests.integration.conftest",+ "-o",+ "addopts=",+ "--integration-shard-count=3",+ f"--integration-shard-index={index}",+ f"--integration-shard-files={files[index]}",+ "--integration-order-seed=1848224111",+ "--hypothesis-seed=4106601",+ "--timeout=15",+ *(("-n", str(workers), "--dist=loadgroup") if workers > 1 else ()),+ "-q",+ ),+ cwd=root,+ env={+ **{+ name: value+ for name, value in os.environ.items()+ if name+ not in (+ "INTEGRATION_RESULTS_DIR",+ "INTEGRATION_ROUTING",+ "GITHUB_ACTIONS",+ "PYTEST_XDIST_WORKER",+ )+ },+ "INTEGRATION_RESULTS_DIR": str(outputs[index]),+ "PYTHONPATH": os.pathsep.join((str(root), str(root / "tests"), str(root / "tests/e2e"))),+ },+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )+ for index in range(3)+ )+ assert all(result.returncode == 0 for result in results), tuple(+ result.stdout + result.stderr for result in results+ )+ executions: Final = tuple(+ ShardExecution.model_validate_json((output / "execution.json").read_text()) for output in outputs+ )+ assert shard_errors(executions, 3) == ()+ assert len(executions[0].inventory) == (2 if subset else 13)+ assert executions[2].collected == ()+ assert executions[2].complete+ assert len(executions[1].skipped) == 1+ assert executions[1].skipped[0].endswith("::test_existing_skip")+ observed: Final = tuple(events.read_text().splitlines())+ assert observed.count("start shared") == observed.count("stop shared") == 1+ assert sorted(event for event in observed if event.startswith("shared ")) == (+ ["shared 1"] if subset else [f"shared {index}" for index in range(4)])- (tmp_path / "partition_probe.py").write_text(- "from integration._support.ordering import case_shards, collected_case\n"- "def pytest_collection_modifyitems(config, items):\n"- " shards = case_shards(tuple(collected_case(item) for item in items), 3)\n"- " selected = shards[config.getoption('integration_shard_index')]\n"- " items[:] = tuple(item for item in items if item.nodeid in selected)\n"+ assert sorted(event for event in observed if event.startswith("plain ")) == (+ [] if subset else [f"plain {index}" for index in range(8)])- results: Final = tuple(- subprocess.run(++[email protected]("assignment", ("absent", "missing", "foreign"))+def test_invalid_native_selections_fail_before_any_case_runs(+ tmp_path: Path, assignment: Literal["absent", "missing", "foreign"]+) -> None:+ root: Final = Path(__file__).resolve().parents[3]+ events: Final = tmp_path / "executed.txt"+ selection: Final = tmp_path / "node-files.txt"+ if assignment == "foreign":+ selection.write_text("tests/integration/database/test_unknown.py\n")+ with TemporaryDirectory(prefix="invalid-selection-", dir=Path(__file__).parent) as directory:+ probe: Final = Path(directory) / "test_probe.py"+ probe.write_text(f"from pathlib import Path\ndef test_case():\n Path({str(events)!r}).write_text('ran')\n")+ result: Final = subprocess.run((sys.executable,"-P","-m","pytest",- str(probe),+ str(probe.relative_to(root)),+ "--noconftest","-p","tests.integration.conftest",- "-p",- "partition_probe",- "--integration-shard-count=3",- f"--integration-shard-index={index}",- "--integration-order-seed=1848224111",- "--timeout=15",+ "-o",+ "addopts=",+ "--integration-shard-count=2",+ "--integration-shard-index=0",+ *((f"--integration-shard-files={selection}",) if assignment != "absent" else ()),"-q",),+ cwd=root,env={**{name: valuefor name, value in os.environ.items()- if name not in ("INTEGRATION_RESULTS_DIR", "INTEGRATION_ROUTING")+ if name not in ("INTEGRATION_RESULTS_DIR", "INTEGRATION_ROUTING", "GITHUB_ACTIONS")},- "PYTHONPATH": os.pathsep.join((str(tmp_path), os.environ.get("PYTHONPATH", ""))),+ "PYTHONPATH": os.pathsep.join((str(root), str(root / "tests"), str(root / "tests/e2e"))),},capture_output=True,text=True,- timeout=30,+ timeout=15,check=False,)- for index in range(3)- )- assert all(result.returncode == 0 for result in results), tuple(result.stdout + result.stderr for result in results)- observed: Final = tuple(events.read_text().splitlines())- assert observed.count("start shared") == observed.count("stop shared") == 1- assert sorted(event for event in observed if event.startswith("shared ")) == [- f"shared {index}" for index in range(4)- ]- assert sorted(event for event in observed if event.startswith("plain ")) == [f"plain {index}" for index in range(8)]+ assert result.returncode == pytest.ExitCode.USAGE_ERROR, result.stdout + result.stderr+ assert not events.exists()@pytest.mark.parametrize("entrypoint", ("gateway", "refused"))diff --git a/tests/integration/run.py b/tests/integration/run.pyindex f89bd15adf9..98b727efce9 100644--- a/tests/integration/run.py+++ b/tests/integration/run.py@@ -60,8 +60,8 @@ def main() -> int:parser.add_argument("--workers", type=int, default=int(os.environ.get("INTEGRATION_WORKERS", "1")))parser.add_argument("--shards", type=int, default=int(os.environ.get("INTEGRATION_CASE_SHARDS", "1")))parser.add_argument("--shard-index", type=int, default=int(os.environ.get("INTEGRATION_CASE_SHARD_INDEX", "0")))- parser.add_argument("--timings", type=Path)- parser.add_argument("--list", action="store_true", help="print the group's test files and exit")+ parser.add_argument("--shard-files", type=Path)+ parser.add_argument("--list", action="store_true", help="print selected candidate files and exit")parser.add_argument("files", nargs="*", help="run only these files, or pytest node ids inside them, of the group")options: Final = parser.parse_intermixed_args()root: Final = Path(__file__).resolve().parents[2]@@ -71,14 +71,14 @@ def main() -> int:for path in sorted((root / "tests/integration" / folder).rglob("test_*.py"))if str(path.relative_to(root)) not in GITHUB_FILES)- if options.list:- sys.stdout.write("\n".join(group_files) + "\n")- return 0selection: Final = select(tuple(options.files), group_files)if selection.foreign:parser.error(f"Not in the {options.group} group: {', '.join(selection.foreign)}")if not selection.nodes:parser.error(f"No integration test files selected for {options.group}")+ if options.list:+ sys.stdout.write("\n".join(sorted({file_of(node) for node in selection.nodes})) + "\n")+ return 0output: Final = options.results.resolve()output.mkdir(parents=True, exist_ok=True)environment: Final = {@@ -109,7 +109,7 @@ def main() -> int:f"--integration-order-seed={options.order_seed}",f"--integration-shard-count={options.shards}",f"--integration-shard-index={options.shard_index}",- *(("--integration-timings", str(options.timings)) if options.timings is not None else ()),+ *(("--integration-shard-files", str(options.shard_files)) if options.shard_files is not None else ()),f"--junitxml={output / 'junit.xml'}","-o","junit_family=xunit1",diff --git a/tests/unit/integration_support/test_ordering.py b/tests/unit/integration_support/test_ordering.pyindex 98b08d0849c..775986c6e98 100644--- a/tests/unit/integration_support/test_ordering.py+++ b/tests/unit/integration_support/test_ordering.py@@ -1,17 +1,12 @@from __future__ import annotationsfrom itertools import groupby-from types import MappingProxyTypefrom typing import Final-import pytest-from tests.integration._support.ordering import (CollectedCase,ScopedParameter,- case_shards,fixture_groups,- parse_timings,)from tests.integration.conftest import _order_key@@ -68,113 +63,3 @@ def test_equal_unhashable_parameters_share_a_group_only_within_their_fixture_ownassert groups[first.nodeid] != groups[other_owner.nodeid]assert groups[first.nodeid] != groups[other_file.nodeid]assert groups[plain.nodeid] == ""---def test_shards_balance_cases_without_splitting_a_scoped_configuration() -> None:- cases: Final = tuple(- CollectedCase(- f"test_slots.py::test_route[{index}]",- (ScopedParameter("module:slots", "rig", index // 4),),- ("module:slots:extra",) if index % 2 else (),- )- for index in range(20)- )- plain: Final = tuple(CollectedCase(f"test_slots.py::test_plain[{index}]") for index in range(7))- shards: Final = case_shards(cases + plain, 3)- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases + plain)- assert sum(len(shard) for shard in shards) == len(cases + plain)- assert max(map(len, shards)) - min(map(len, shards)) <= 1- for _, group in groupby(cases, key=lambda case: case.parameters[0].value):- configuration: Final = frozenset(case.nodeid for case in group)- assert sum(configuration <= shard for shard in shards) == 1- assert shards == case_shards(tuple(reversed(cases + plain)), 3)---def test_shards_reuse_unparametrized_fixtures_and_keep_different_results_separate() -> None:- shared: Final = tuple(- CollectedCase(f"test_sockets.py::test_override[{index}]", fixtures=("module:test_sockets.py:override",))- for index in range(4)- )- other: Final = CollectedCase("test_sockets.py::test_default", fixtures=("module:test_sockets.py:default",))- plain: Final = tuple(CollectedCase(f"test_other.py::test_plain[{index}]") for index in range(7))- shards: Final = case_shards((*shared, other, *plain), 3)- configuration: Final = frozenset(case.nodeid for case in shared)- assert sum(configuration <= shard for shard in shards) == 1- assert sorted(map(len, shards)) == [4, 4, 4]- assert frozenset.union(*shards) == frozenset(case.nodeid for case in (*shared, other, *plain))- groups: Final = fixture_groups((*shared, other))- assert len({groups[case.nodeid] for case in shared}) == 1- assert groups[other.nodeid] != groups[shared[0].nodeid]- assert shards == case_shards(tuple(reversed((*shared, other, *plain))), 3)---def test_an_oversized_unparametrized_fixture_is_split_into_bounded_groups() -> None:- cases: Final = tuple(- CollectedCase(f"test_sockets.py::test_route[{index:02}]", fixtures=("module:test_sockets.py:owned",))- for index in range(20)- )- shards: Final = case_shards(cases, 4)- assert tuple(map(len, shards)) == (5, 5, 5, 5)- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)- assert sum(len(shard) for shard in shards) == len(cases)---def test_measured_cost_splits_an_expensive_shared_fixture_without_losing_cases() -> None:- expensive: Final = tuple(- CollectedCase(f"test_tracing.py::test_route[{index}]", fixtures=("module:test_tracing.py:gateway",))- for index in range(4)- )- cheap: Final = tuple(CollectedCase(f"test_other.py::test_route[{index}]") for index in range(8))- cases: Final = (*expensive, *cheap)- durations: Final = MappingProxyType({case.nodeid: 40.0 if case in expensive else 1.0 for case in cases})- shards: Final = case_shards(cases, 4, durations)- assert sorted(sum(durations[nodeid] for nodeid in shard) for shard in shards) == [42.0] * 4- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)- assert sum(len(shard) for shard in shards) == len(cases)- assert shards == case_shards(tuple(reversed(cases)), 4, durations)--- "content",- (- "invalid",- "{}",- '[{"nodeid":"case","seconds":-1}]',- '[{"nodeid":"case","seconds":"1"}]',- '[{"nodeid":"case","seconds":NaN}]',- '[{"nodeid":"case","seconds":Infinity}]',- '[{"nodeid":"case","seconds":1},{"nodeid":"case","seconds":2}]',- ),-)-def test_invalid_timing_cache_preserves_the_complete_cold_partition(content: str) -> None:- cases: Final = tuple(CollectedCase(f"test_owned.py::test_route[{index}]") for index in range(9))- durations: Final = parse_timings(content)- assert not durations- assert case_shards(cases, 3, durations) == case_shards(cases, 3)---def test_timing_cache_keeps_zero_duration_skips_and_assigns_new_cases() -> None:- durations: Final = parse_timings('[{"nodeid":"skip","seconds":0},{"nodeid":"old","seconds":12}]')- cases: Final = (CollectedCase("skip"), CollectedCase("new"))- shards: Final = case_shards(cases, 2, durations)- assert durations["skip"] > 0- assert frozenset.union(*shards) == frozenset({"skip", "new"})- assert tuple(map(len, shards)) == (1, 1)---def test_measured_cost_keeps_parametrized_fixture_configurations_atomic() -> None:- shared: Final = tuple(- CollectedCase(- f"test_tracing.py::test_route[{index}]",- (ScopedParameter("module:test_tracing.py", "configuration", "shared"),),- )- for index in range(3)- )- plain: Final = tuple(CollectedCase(f"test_other.py::test_route[{index}]") for index in range(5))- cases: Final = (*shared, *plain)- durations: Final = MappingProxyType({case.nodeid: 40.0 if case in shared else 1.0 for case in cases})- shards: Final = case_shards(cases, 3, durations)- configuration: Final = frozenset(case.nodeid for case in shared)- assert sum(configuration <= shard for shard in shards) == 1- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)- assert sum(len(shard) for shard in shards) == len(cases)diff --git a/tests/unit/integration_support/test_sharding.py b/tests/unit/integration_support/test_sharding.pyindex 3d3b53b6f51..2317279f2b2 100644--- a/tests/unit/integration_support/test_sharding.py+++ b/tests/unit/integration_support/test_sharding.py@@ -2,14 +2,14 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom dataclasses import dataclass+from pathlib import Pathfrom types import MappingProxyTypefrom typing import Finalimport pytest-from tests.integration._support.ordering import CaseTiming-from tests.integration._support.sharding import ShardExecution, merged_timings, shard_errors-from tests.integration.conftest import COLLECTED, IntegrationReportPlugin+from tests.integration._support.sharding import ShardExecution, shard_errors+from tests.integration.conftest import COLLECTED, IntegrationReportPlugin, _shard_filesfrom tests.integration.conftest import INVENTORY as WORKER_INVENTORYINVENTORY: Final = ("test_owned.py::test_first", "test_owned.py::test_skipped", "test_owned.py::test_last")@@ -46,10 +46,34 @@ def test_shard_qualification_retains_passes_and_skip_identities() -> None:assert shard_errors(executions, 2) == ()+def test_a_selected_subset_can_leave_a_shard_empty_without_losing_the_inventory() -> None:+ executions: Final = (_execution(0, INVENTORY), _execution(1, ()))+ assert shard_errors(executions, 2) == ()+ assert shard_errors((_execution(0, INVENTORY[:1]), _execution(1, ())), 2)+++def test_an_empty_assignment_is_distinct_from_no_assignment_or_a_missing_file(tmp_path: Path) -> None:+ assignment: Final = tmp_path / "node-files.txt"+ assert _shard_files(None) is None+ with pytest.raises(pytest.UsageError, match="Cannot read"):+ _shard_files(assignment)+ assignment.write_text("")+ assert _shard_files(assignment) == frozenset()++[email protected]("content", ("test_owned.py\ntest_owned.py\n", "test_owned.py\n\n", "\n"))+def test_an_invalid_assignment_is_rejected_instead_of_running_extra_tests(tmp_path: Path, content: str) -> None:+ assignment: Final = tmp_path / "node-files.txt"+ assignment.write_text(content)+ with pytest.raises(pytest.UsageError, match="duplicate or blank"):+ _shard_files(assignment)++@pytest.mark.parametrize("executions",((),+ (_execution(0, (), inventory=()), _execution(1, (), inventory=())),(_execution(0, INVENTORY),),(_execution(0, INVENTORY[:2]), _execution(0, INVENTORY[2:])),(_execution(0, INVENTORY[:1]), _execution(1, INVENTORY[2:])),@@ -70,34 +94,6 @@ def test_shard_qualification_rejects_lost_duplicate_foreign_or_failed_cases(assert shard_errors(executions, 2)-def test_timing_snapshot_includes_every_executed_pass_and_skip_once() -> None:- first: Final = CaseTiming(nodeid=INVENTORY[0], seconds=40.0)- skipped: Final = CaseTiming(nodeid=INVENTORY[1], seconds=0.0)- last: Final = CaseTiming(nodeid=INVENTORY[2], seconds=1.0)- executions: Final = (- _execution(0, INVENTORY[:2], skipped=INVENTORY[1:2]).model_copy(update={"timings": (first, skipped)}),- _execution(1, INVENTORY[2:]).model_copy(update={"timings": (last,)}),- )- assert shard_errors(executions, 2) == ()- assert merged_timings(executions) == tuple(sorted((first, skipped, last), key=lambda timing: timing.nodeid))--- "timings",- (- (),- (CaseTiming(nodeid=INVENTORY[0], seconds=1.0),),- (CaseTiming(nodeid=INVENTORY[0], seconds=1.0),) * 2,- (CaseTiming(nodeid="foreign", seconds=1.0), CaseTiming(nodeid=INVENTORY[1], seconds=0.0)),- ),-)-def test_incomplete_duplicate_or_foreign_measurements_cannot_seed_the_timing_cache(- timings: tuple[CaseTiming, ...],-) -> None:- execution: Final = _execution(0, INVENTORY[:2]).model_copy(update={"timings": timings})- assert merged_timings((execution,)) == ()--@dataclass(frozen=True, slots=True)class WorkerResult:workeroutput: Mapping[str, object]