Skip to content

Python

langadapter.python.adapter

The Python adapter bound to one project context. Its language facts and capability report come from the context's own interpreter, locally or in the container, never from the calling process.

VOCABULARY module-attribute

VOCABULARY: Dict[str, str] = {'valid_source': 'valid Python', 'real_source': 'real Python', 'test_declaration': '``def test_*(...)``', 'test_declaration_full': '``def test_*(...):`` function', 'collection_rule': 'Pytest only collects functions whose names start with ``test_`` (or methods on classes starting with ``Test``).', 'fixture_term': 'fixtures', 'parametrize_term': '``@pytest.mark.parametrize``', 'single_file_rule': 'Produce one ``test_*.py`` file. Do not create helper files or runner scripts.', 'test_file': '``test_<target_stem>.py``', 'import_rule': 'imports the target module', 'load_error': 'collection error', 'fake_builtin_rule': '- When a test must fake a built-in function, replace it only in the\n  module under test, for example\n  ``monkeypatch.setattr(module, "len", fake, raising=False)``, not in\n  ``builtins``. To simulate a missing optional package, use\n  ``monkeypatch.setitem(sys.modules, "name", None)``.', 'exception_assertion': '``pytest.raises``', 'timeout_marker': '``@pytest.mark.timeout({seconds})``', 'parse_error_hints': 'missing colon at end of def/if/for, unbalanced brackets/parens/quotes, mismatched indentation, accidental code-fence remnants', 'test_dependencies': "Test toolkit (always available):\n  - pytest (the runner; @pytest.fixture, @pytest.mark.parametrize, @pytest.mark.timeout, pytest.raises)\n  - unittest.mock (stdlib; Mock, MagicMock, patch, patch.object, sentinel)\nThe project's own ``import`` graph is also available (import the module under test directly). Third-party libraries beyond pytest + unittest.mock are only available if the project's ``requirements.txt`` / ``pyproject.toml`` declares them; check before importing unfamiliar names.", 'validity_rule': "Allowed: the target's runtime behaviour and documented metadata (attributes, __dict__ and vars(), __name__, __doc__, annotations, inspect.signature). Forbidden: reading or analysing its source text (inspect.getsource, its file) or bytecode (__code__, dis), executing copied source, or attributing synthetic code to its source locations.", 'stands_alone_advice': "  1. A test must leave the module under test as it found it. Change\n     it only through monkeypatch, which restores what it set, or\n     restore it in a fixture; reloading the module in place replaces\n     every function and class the later tests use. To run import-time\n     code (an ``if TYPE_CHECKING:`` block, an ``except ImportError:``\n     fallback), reload it in a fixture that first saves\n     ``dict(module.__dict__)`` as ``saved`` and afterwards restores it\n     with ``module.__dict__.clear()`` and ``module.__dict__.update(saved)``.\n  2. A test must restore a library setting it changes: use the\n     library's context manager (np.errstate, np.printoptions,\n     xr.set_options) or save and restore the setting in a fixture.\n  3. A test must not rely on the measurement's fixed random seed or on\n     dask's default scheduler: seed or configure what it uses.", 'load_error_patterns': "  - ImportError -> verify the name actually exists in the\n    target module / fix the import path.\n  - SyntaxError / IndentationError -> check the working file for\n    unbalanced brackets, bad indentation, stray characters from\n    a previous edit.\n  - NameError at module top-level -> ensure the name is\n    imported / defined before it's used."}

Python's words for its tests (langadapter.vocabulary), for a project whose pytest has the timeout mark (PythonAdapter.test_vocabulary). Caller-facing text: changed only on purpose.

PythonAdapter

PythonAdapter(context: ProjectContext, executor: Optional[Executor] = None)

Bases: PythonSources

Python projects: pytest, coverage.py and Cosmic Ray in the project environment, tree-sitter and the Python parser in this process.

language class-attribute instance-attribute

language = 'python'

file_extensions class-attribute instance-attribute

file_extensions = ('.py',)

source_execution_kinds class-attribute instance-attribute

source_execution_kinds = ('local', 'container')

source_merge_separator class-attribute instance-attribute

source_merge_separator = '#'

test_execution_kinds class-attribute instance-attribute

test_execution_kinds = ('local', 'container')

native_mutation_engines class-attribute instance-attribute

native_mutation_engines = ('cosmic_ray',)

mutation_execution_kinds class-attribute instance-attribute

mutation_execution_kinds = ('local', 'container')

mutation_evidence_granularity class-attribute instance-attribute

mutation_evidence_granularity = ('aggregate', 'per_mutant', 'per_test')

test_evidence_granularity class-attribute instance-attribute

test_evidence_granularity = (('run_suite', ('aggregate', 'per_test')), ('run_as_delivered', ('aggregate', 'per_test')), ('benchmark', ('aggregate',)), ('per_test_evidence', ('per_test',)))

support class-attribute instance-attribute

support = SUPPORT

What the Python adapter supports (LanguageSupport).

validity_policy_version class-attribute instance-attribute

validity_policy_version = VALIDITY_POLICY_VERSION

The version of the generated-test validity policy whose findings analyze_validity and screen_source report.

display_name class-attribute instance-attribute

display_name = 'Python'

runtime class-attribute instance-attribute

runtime = 'python'

The program that runs the tests. The project's interpreter is the context's, found as the project setup finds it.

test_file_name class-attribute instance-attribute

test_file_name = 'test_{stem}.py'

test_framework class-attribute instance-attribute

test_framework = 'pytest'

code_fence class-attribute instance-attribute

code_fence = 'python'

collection_unit class-attribute instance-attribute

collection_unit = COLLECTION_UNIT

reuses_bytecode class-attribute instance-attribute

reuses_bytecode = True

copies_external_suite class-attribute instance-attribute

copies_external_suite = True

seeds_delivered_runs class-attribute instance-attribute

seeds_delivered_runs = True

Its run as delivered takes a session seed (run_as_delivered).

unmatched_evidence_kept class-attribute instance-attribute

unmatched_evidence_kept = True

Per-test evidence keeps the coverage contexts no reported test claims, a test run under its own context but missing from the report (LanguageFacts.unmatched_evidence_kept).

coverage_matrix_in_place class-attribute instance-attribute

coverage_matrix_in_place = True

non_source_files class-attribute instance-attribute

non_source_files = ('setup.py',)

The build script a project's directory may hold beside its sources.

project_settings class-attribute instance-attribute

project_settings = (ProjectSetting('python_executable', "The project's Python interpreter. Empty: the environment uv provisions for python_version, else the project's only environment, its .venv or the one activated in the shell. The environment the caller runs in counts only inside the project. Two environments, or none, refuse the run.", 'executable', check='an interpreter that starts', host_path='path'), ProjectSetting('python_version', 'A Python version, for example 3.12, for which uv provisions an environment when python_executable is empty.', 'text', check='a version uv can provision'), ProjectSetting('requirements', 'Requirements file for the environment provisioned by python_version.', 'path', check='a file', host_path='host file'), ProjectSetting('python_import_root', 'The directory below the project from which its Python package is imported, for example src. Empty imports from the project directory itself.', 'path', check='a directory below the project'), ProjectSetting('python_test_environment', "Variables the processes of the Python adapter's own runs get, as NAME=value words, for example PURE_PYTHON=1. Python tests of a C extension do not get them.", 'text', check='NAME=value words'), ProjectSetting('frozen_module_strategy', "unfreeze runs the project's Python with -X frozen_modules=off, so coverage and mutation treat the standard library's frozen modules as ordinary files. skip leaves them frozen.", 'choice', default='unfreeze', choices=('unfreeze', 'skip'), check='one of the choices'), ProjectSetting('pytest_config', "auto uses the target project's pytest configuration when present. An explicit path selects a configuration file, and none selects pytest defaults.", 'path', default='auto', check='auto, none or a file'))

A Python project's settings.

test_of_nodeid class-attribute instance-attribute

test_of_nodeid = staticmethod(test_of_nodeid)

test_of_nodeid(nodeid): the test a pytest node id names, relative to the suite's root, file::Class::function[params], the parameters apart. Another adapter whose Python tests pytest runs reads their node ids this way.

executor instance-attribute

executor = executor or executor_for(context)

interpreter property

interpreter: str

The project interpreter's path as the executing side sees it. A provisioning request must be fulfilled first.

test_vocabulary

test_vocabulary() -> Dict[str, str]

Python's words for its tests (VOCABULARY), without the timeout mark where the project's pytest lacks it.

test_id_text

test_id_text(test) -> str

A test's dotted id, as coverage's contexts and the kill matrices write it: the file's path without its suffix, then the qualified name (tests.test_calc.TestCalc.test_adds).

kill_tokens

kill_tokens(kill_matrix, test_ids)

The kill tokens of the recorded killing tests, and a crash token (C:<mutant id>) for the test a kill without a named killer ended in (active_at_end), matched as coverage's contexts are.

request_options

request_options(purpose: str, *, target: Optional[str] = None, traceback: Optional[str] = None, stop_at_first_failure: bool = False, record_leaks: bool = False, session_seed: Optional[int] = None, reverse_order: bool = False, leave_out_timing_plugins: bool = False) -> Dict[str, Any]

The isolated pytest configuration, module under test and pytest options of each kind of run, logfire and anyio plugins off: a test run with the caller's traceback (short by default), first-failure stopping and leak record, a run as delivered with the caller's traceback (pytest's own by default), first-failure stopping, session seed, order and leak record and, when the caller names a target, the module under test, which in a prepared project also decides which file the run imports (the copy's) and is the module the leak record compares. Timing and a coverage matrix without a traceback. Test runs, failing-tests runs, per-test evidence and runs as delivered remove the files tests create. The project's own run keeps its configuration and disables no plugin. leave_out_timing_plugins reaches every purpose's pytest options.

collection_text

collection_text(run) -> str

pytest's collection exception summary (CollectionRun.diagnostic).

salvage_report

salvage_report(source: str)

python.source_analysis.salvage_syntax with the project interpreter's verdicts through sources.validate_source. A verdict it could not give reads timeout or validator_error with its reason.

skip_removal

skip_removal(source: str)

python.source_analysis.strip_module_level_skips, by the calling process's parser.

collision_dependents

collision_dependents(source: str, name: str, measured)

python.source_analysis.collision_dependents.

collision_resolution

collision_resolution(sources, *, localize_autouse: bool = False, preference=None)

python.source_analysis.resolve_collisions, by the calling process's parser, always completed.

context_environment classmethod

context_environment(values, *, container=False)

The variables python_test_environment gives the processes of this adapter's runs, and python_import_root as IMPORT_ROOT_VARIABLE: the directory below the project root, src for src/ (. and none name the project itself, which needs no variable). A directory outside the project is refused.

discover_runtime classmethod

discover_runtime(root, values, *, container=False, environment=None, resolve_path=None)

The selected interpreter, else a provisioning request for python_version (with its requirements), else the project's only environment. InvalidRequest names python_executable when none can be chosen. On this machine a selection is the path resolve_path gives and must exist. In a container it is required, taken as given, and as an absolute POSIX path can supervise the container's commands. Under unfreeze the interpreter runs with -X frozen_modules=off. The test framework follows pytest_config.

describe_runtime classmethod

describe_runtime(root, values, *, container=False, environment=None, resolve_path=None)

The selection as discover_runtime reads it, without checking that a selected interpreter exists and without discovering one: no interpreter when none is selected and no python_version asks for one.

setup_questions classmethod

setup_questions(project_dir, probe, *, consumer='the caller')

The import directory and the interpreter.

setup_problem classmethod

setup_problem(setting, value, project_dir, probe)

The import directory must exist, the interpreter run and be supported. The other settings are checked by their kind.

provision_runtime classmethod

provision_runtime(request, *, store, name, environment=None, log=None)

The interpreter of the environment uv makes for the requested Python version, with its requirements file and the tools LangAdapter pins for that Python.

mutation_catalogue

mutation_catalogue(config)

The catalogue cosmic_ray_operators names.

named_operators

named_operators(name: str)

Cosmic Ray's named operator set.

mutation_session_attempts

mutation_session_attempts(config, *, configured_workers: int, effective_workers: int, cache_base: str, log=None)

Cosmic Ray's distributor and worker rule and its settings.

mutation_dir_refusal

mutation_dir_refusal(config, *, create: bool)

cosmic_ray_local_session_dir's check.

mutation_workers_refusal

mutation_workers_refusal(config)

Why the distributor cannot run the configured workers, or None.

setup_files

setup_files(root: str, test_paths) -> Tuple[str, ...]

The conftest files pytest loads between root and each test file (python.project.loaded_setup_files).

shared_setup_files

shared_setup_files(directory: str) -> Tuple[str, ...]

A prepared suite's conftest.py (python.project.setup_files).

test_files

test_files(paths)

Each path, a directory replaced by the test files pytest collects in it, asked with a run's settings.

project_test_files

project_test_files()

The test files pytest collects in the project as its configuration bounds them, its testpaths included: a collection from the context's root with no file or directory named.

coverage_texts

coverage_texts(coverage) -> Dict[str, Tuple[Any, ...]]

The covered statements, as Java's are (not the lines coverage.py traced, which include a docstring's line), and each missed arc, as exit:N for one that leaves the code object starting at line N (a function's def or first decorator), so a reader can name the function it leaves, also one never called. Caller-facing text.

delivered_case

delivered_case(test, outcome: str) -> Tuple[str, str, str]

The module's stem and qualified name, the name with its parameters in brackets, and the outcome, an expected failure that failed as skipped.

import_statement classmethod

import_statement(target: str, root: str) -> str

The dotted module of target from the project's root, bound through importlib where the package binds that name itself. Caller-facing text.

code_smells

code_smells(paths) -> Optional[int]

The number of ruff's findings in paths, or None when ruff is missing or fails.

run_counts

run_counts(run) -> Dict[str, Optional[int]]

The counts of pytest's own summary, from the run record (SuiteRun.runner_counts), with collected the passed, failed, errored and skipped tests, less one per file pytest could not collect. All None for a run that ended before its session did.

listed_failures

listed_failures(run)

The report's failed and errored cases, whatever the exit status (after pytest's internal error, the tests that ran before it. Its synthetic and nameless records are unmatched entries). None for a timeout, a collection error, no tests, a run that could not start or a report naming no test.

inspect_project

inspect_project(request)

Start the selected interpreter in isolation and read its installed tool versions, without site or project imports. Without a selection the only environment found (the project's .venv or the activated one) is selected. Several need a choice. Installed metadata does not prove readiness: verify_project imports the tools.

verify_project

verify_project(request)

Import the needed tools in a prepared copy, installing nothing. It does not certify project collection or measurements.

runtime_version

runtime_version() -> Optional[str]

The interpreter's version line (Python 3.10.16), read once per instance: the context's stated version, else --version run where the project runs. None when it cannot be read, and in a source-only context, which has no interpreter.

choose_profile

choose_profile() -> PythonProfile

The project interpreter's profile against the Python declaration, from versions this instance reads anyway, so it starts no process: the context's stated version, the library's own for its own interpreter, else the toolchain probe every run's identity carries (read before the first operation's timed interval). Only a program that cannot run that probe (Python 2, 3.7 and older) is asked for its version line.

language_facts

language_facts() -> LanguageFacts

Python's facts for this project: pytest, its test name patterns, the interpreter's version, and pytest-timeout's mark when its plugin is registered in the project environment.

capabilities

capabilities() -> CapabilityReport

What this adapter can do for its context, by a project probe.

toolchain_identity

toolchain_identity() -> ToolchainIdentity

The interpreter's implementation and version and the versions of the project environment's tools, probed once per instance. A probe that failed is asked again by the next call.

operation_readiness

operation_readiness(name: str, report: CapabilityReport)

An execution-backed operation's readiness from the probe: missing setup when the probe did not complete, available for the syntax check and the target's identity, Cosmic Ray for the operator catalogue, and the probe's capabilities for the rest.

run_suite

run_suite(request: Any) -> Any

Run a suite (langadapter.runs.SuiteRunRequest) and return its SuiteRun: the outcome, the counts, every test's outcome by identifier, the wall time, the whole output, the coverage of the target when one is named, the identity and the side effects applied. An invalid request raises InvalidRequest.

collect_suite

collect_suite(request: Any) -> Any

Collect explicit suite files without running their test bodies (CollectionRequest to CollectionRun). A collection failure, an empty collection and failed execution stay distinct.

run_as_delivered

run_as_delivered(request: Any, *, sources: Any = None) -> Any

Run each test file alone, without the measurement instrument, for a SuiteRunRequest with session_seed. sources may replace a listed test file's text without overwriting it. The SuiteRun's test IDs refer to the input suite.

prepare_suite

prepare_suite(suite_root: str, *, isolation_config: bool = False) -> Any

Write setup for a generated suite (SuitePreparation): the import shim, and a configuration anchor only when requested. Ordinary suite runs never call it implicitly.

benchmark

benchmark(request: Any) -> Any

Time a suite (langadapter.runs.BenchmarkRequest) over repeated runs and return the measured repetitions' times (Benchmark). An invalid request raises InvalidRequest.

profile_suite

profile_suite(request: Any) -> Any

A suite profile (langadapter.runs.SuiteProfileRequest): the suite run once with the standard library's cProfile around each test's setup, call and teardown, and the time of each function it entered (SuiteProfile). Interpreter start, imports and collection are not profiled.

per_test_evidence

per_test_evidence(request: Any) -> Any

Per-test evidence (langadapter.runs.PerTestEvidenceRequest) of a green run: each test's covered lines and arcs of the target, its time, and the mutants it kills when a mutation run is given (PerTestEvidence). An invalid request raises InvalidRequest.

mutation_engines

mutation_engines() -> Tuple[str, ...]

The mutation engines this adapter offers for its context: Cosmic Ray when it is installed in the project environment.

mutation_operators

mutation_operators(engine: str = 'cosmic_ray') -> Any

The operators engine registers in the project environment (an OperatorCatalogue), read through the project interpreter and sorted: the full catalogue a run measures by default. Cosmic Ray absent there is missing_setup, an unreadable registry infrastructure_failure.

open_mutation_session

open_mutation_session(engine: str = 'cosmic_ray', **options: Any) -> Any

A mutation session of engine for this adapter's project. workers is how many mutants are measured at once (1 by default), distributor auto (the default), local or http. allow_fewer_workers opens the session with the HTTP workers that started when fewer than workers did. settings is a python.cosmic_ray.CosmicRaySettings.

validate_mutation_session_options

validate_mutation_session_options(engine: str, **options: Any) -> None

Refuse a Cosmic Ray session option it does not accept, such as an unknown distributor, with InvalidRequest.

check_structure

check_structure(source: str) -> Any

Whether source parses, with its first error (StructureCheck).

structural_parser_identity

structural_parser_identity() -> str

The structural parser and grammar used by source operations.

test_metrics

test_metrics(source: str) -> Any

The counts of a test source, absent when the structural parser or the library's Python parser, which reads its tests, rejects it (TestMetrics).

skeleton

skeleton(source: str) -> Tuple[str, ...]

Qualified function/class names from the calling process's grammar.

same_skeleton

same_skeleton(first: str, second: str) -> Tuple[bool, str]

Whether sources have the same static definition names, with a reason.

function_fingerprints

function_fingerprints(source: str) -> Dict[str, str]

Static per-definition fingerprints, excluding comments.

optimization_metrics

optimization_metrics(source: str) -> Dict[str, Any]

Static structural metrics. These are not execution measurements.

scoped_optimization_metrics

scoped_optimization_metrics(source: str) -> Any

The structural metrics of source per declaration (scoped metrics).

call_statistics

call_statistics(source: str) -> Optional[Dict[str, int]]

The call sites of source by called name, None when it does not parse: the call search of sources.call_statistics.

imports

imports(source: str) -> Tuple[str, ...]

Static import names in source order, relative ones kept relative. An unparseable source gives none (check_structure tells it from a source without imports).

import_path_candidates

import_path_candidates(name: str) -> Tuple[str, ...]

Possible source paths of an absolute import, without resolving it.

duplicate_test_names

duplicate_test_names(source: str) -> list[str]

Test bindings shadowed in the same source scope. A source this process's parser cannot read raises SourceReadError.

merge_collisions

merge_collisions(first: str, second: str) -> Tuple[str, ...]

Top-level function and class names and module-level assignment names that two sources share, without rewriting.

stage_pool

stage_pool(members: Any, *, setup: Any = ()) -> Any

Several suites' test files as one pool, each file named for its suite (langadapter.sources.StagedPool).

is_test_file

is_test_file(path: Any) -> bool

Recognize pytest/unittest filenames, including setup files.

order_dependent_mock_warnings

order_dependent_mock_warnings(source: str) -> list[str]

Tests that assert on a named element of a mock's side_effect list, whose order a scheduler in the code under test can change (advisory). A source this process's parser cannot read raises SourceReadError.

validate_source

validate_source(source: str) -> Any

SourceValidation: whether the project interpreter compiles source.

prune_tests

prune_tests(source: str, tests: Any) -> Any

source without the named tests (SourceResult).

merge_sources

merge_sources(first: str, second: str, *, separator: str) -> Any

Two test modules as one (SourceResult).

normalize_shadowed

normalize_shadowed(source: str) -> Any

source without shadowed definitions (SourceResult).

normalize_bindings

normalize_bindings(source: str) -> Any

Static full binding report, without target-runtime validation.

normalization_parser_identity

normalization_parser_identity() -> str

The calling interpreter's AST grammar used for binding analysis.

resolve_collisions

resolve_collisions(sources: Any, *, preference: Any = None, localize_autouse: bool = False) -> Any

Module-level name collisions among test sources resolved before they are merged into one module, as a SourceObservation of a CollisionResolution. Without a preference a conflict is reported and nothing dropped.

salvage_syntax

salvage_syntax(source: str) -> Any

A bounded repair of a source the project interpreter does not compile (SourceResult, a generated-suite operation).

prune_unresolvable_imports

prune_unresolvable_imports(source: str) -> Any

source without imports that do not resolve in the project environment (SourceResult, a generated-suite operation).

prune_collection_breakers

prune_collection_breakers(source: str, *, timeout_s: float) -> Any

source with the module-level or class-level statements that break pytest's collection replaced by pass (SourceResult, a generated-suite operation).

strip_module_level_skips

strip_module_level_skips(source: str) -> Any

source without module-level skip guards (SourceResult, a generated-suite operation).

target_identity

target_identity(target: str) -> Any

The identity of a file under test for the generated-test validity policy (TargetIdentity): its module named from the import root (python_import_root below the project root), as the tests import it.

analyze_validity

analyze_validity(source: str, target: Any) -> Any

The validity policy's findings on a generated test source (PolicyReport, a generated-suite operation).

screen_source

screen_source(source: str, target: Any) -> Any

The policy's review-only screening signals on a generated test source (PolicyReport, a generated-suite operation).

finalize_source

finalize_source(source: str) -> Any

source without detached comment blocks (SourceResult).

langadapter.python.cosmic_ray

Configuration of the Python adapter's Cosmic Ray mutation sessions, and the attribution of named pytest killers to measured tests in their owning suite.

SessionFolderRefused

Bases: OSError

The configured node-local session directory cannot hold the session. The run is refused rather than moved, since a session on a shared network file system slows every mutant's run.

CosmicRaySettings dataclass

CosmicRaySettings(init_timeout_s: int = 600, worker_ready_timeout_s: int = 60, catalogue_cache_dir: Optional[str] = None, cache_max_entries: int = 200, cache_max_age_days: int = 0, clone_dir: Optional[str] = None, clone_sweep_hours: float = 12, session_dir: Optional[str] = None, local_session_dir: Optional[str] = None, progress_interval_s: int = 0, per_file_adjudication: bool = True, keep_output: bool = False, verbose: bool = False, log: Optional[Callable[..., None]] = None)

Cosmic Ray's own settings for a session. Every value has a default. catalogue_cache_dir (an absolute path) enables the content-hashed catalogue cache. keep_output keeps each mutant's test output in its kill-matrix row. log receives the engine's log lines (log(message, level)). session_dir holds a local run's session database. local_session_dir is the node-local directory of the live session database: a container run's launcher keeps it there (unset: memory-backed storage, then the system's temporary directory), and a local run without session_dir keeps its own directory below it (unset: the system's temporary directory). A configured directory that cannot be made or written refuses the run. Every run logs where its session ran. verbose turns on Cosmic Ray's informational log (host runs only).

init_timeout_s class-attribute instance-attribute

init_timeout_s: int = 600

worker_ready_timeout_s class-attribute instance-attribute

worker_ready_timeout_s: int = 60

catalogue_cache_dir class-attribute instance-attribute

catalogue_cache_dir: Optional[str] = None

cache_max_entries class-attribute instance-attribute

cache_max_entries: int = 200

cache_max_age_days class-attribute instance-attribute

cache_max_age_days: int = 0

clone_dir class-attribute instance-attribute

clone_dir: Optional[str] = None

clone_sweep_hours class-attribute instance-attribute

clone_sweep_hours: float = 12

session_dir class-attribute instance-attribute

session_dir: Optional[str] = None

local_session_dir class-attribute instance-attribute

local_session_dir: Optional[str] = None

progress_interval_s class-attribute instance-attribute

progress_interval_s: int = 0

per_file_adjudication class-attribute instance-attribute

per_file_adjudication: bool = True

keep_output class-attribute instance-attribute

keep_output: bool = False

verbose class-attribute instance-attribute

verbose: bool = False

log class-attribute instance-attribute

log: Optional[Callable[..., None]] = None

check_local_session_dir

check_local_session_dir(configured: Optional[str]) -> None

Check that configured (CosmicRaySettings.local_session_dir) can hold a local run's live session: a missing directory is made, and one that cannot be made, or in which no directory can be made, raises SessionFolderRefused with the cause. An empty value passes. A local run applies the same rule when its session starts, so a caller can refuse early with the run's own text. A directory inside a container only the run's launcher can check.

operator_set_names

operator_set_names() -> Tuple[str, ...]

The names of the operator sets the Python adapter defines for Cosmic Ray, such as wong_mathur_selective.

operator_set

operator_set(name: str) -> Tuple[str, ...]

The operators of the set name as Cosmic Ray names them, fixed by its definition without a project environment. A request takes a set as Catalogue(name=...). An unknown name raises InvalidRequest.

langadapter.python.project

Python suite setup, pytest configuration, interpreter environments and the bytecode store.

A suite staged outside the project would make pytest search the suite's ancestors for a configuration and collect unrelated directories, so the project's configuration is copied beside it and named with -c (isolation_args). A fresh prepared copy compiles every module again, so BytecodeStore keeps what one session's copies compiled and writes it into each new copy outside the timed intervals: pass it as prepare_project(..., bytecode=store).

SuitePreparation dataclass

SuitePreparation(outcome: Outcome, reason: str = '', setup_files: Tuple[str, ...] = (), isolation_files: Tuple[str, ...] = ())

The setup written, including files left by a partially failed write. isolation_files holds the path of the anchoring pytest.ini written into the suite root on request.

outcome instance-attribute

outcome: Outcome

reason class-attribute instance-attribute

reason: str = ''

setup_files class-attribute instance-attribute

setup_files: Tuple[str, ...] = ()

isolation_files class-attribute instance-attribute

isolation_files: Tuple[str, ...] = ()

PytestOptions dataclass

PytestOptions(traceback: str = 'short', stop_at_first_failure: bool = False, disabled_plugins: tuple[str, ...] = (), leave_out_timing_plugins: bool = False)

Traceback style, first-failure stopping, disabled pytest plugins and, with leave_out_timing_plugins, the plugins that change a run's time left out where the project's pytest loads them: pytest-cov's tracer (--no-cov), pytest-xdist's workers (-n 0) and pytest-benchmark's measurement (--benchmark-disable). The project's own options for them stay valid.

traceback class-attribute instance-attribute

traceback: str = 'short'

stop_at_first_failure class-attribute instance-attribute

stop_at_first_failure: bool = False

disabled_plugins class-attribute instance-attribute

disabled_plugins: tuple[str, ...] = ()

leave_out_timing_plugins class-attribute instance-attribute

leave_out_timing_plugins: bool = False

validate

validate() -> None

Refuse an unknown traceback style, a disabled plugin that is no plugin name or a leave_out_timing_plugins that is no boolean with InvalidRequest, naming the field.

BytecodeStore

BytecodeStore(owned: OwnedDirectory)

An owned directory of compiled modules, keyed by the compiling interpreter (magic number, cache tag), the part of the copy (the project or a suite directory beside it), the path in that part and the source's SHA-256. The project's interpreter writes into a copy only its own entries of unchanged sources, and stores a module only when its code equals a fresh compile. Entries are written whole, so sharing sessions never see a partial one. close removes the directory.

root property

root: str

The store's directory.

create classmethod

create(*, parent: Optional[str] = None, receipt_parent: Optional[str] = None) -> 'BytecodeStore'

A new store below parent, by default the system's temporary directory. A container's commands reach only a store in its work directory.

close

close() -> None

Remove the store. A store whose ownership cannot be verified is kept, and OwnershipRefused is raised.

seed

seed(context: ProjectContext, parts: Sequence[Tuple[str, str]]) -> Optional[int]

Write the stored modules of each part's sources beside them, and return the number written (None without a count). A part is a name and its sources' directory as the context's commands see it. Entries are kept by part and relative path, so a copy placing a part elsewhere finds them.

harvest

harvest(context: ProjectContext, parts: Sequence[Tuple[str, str]]) -> Optional[int]

Store the modules the context's runs compiled below each part's directory, and return the number stored: None without a count or after a cancel, whose shortened runs leave nothing worth keeping.

prepare_suite

prepare_suite(adapter, suite_root: str, *, isolation_config: bool = False) -> SuitePreparation

Write conftest.py, the import shim, into suite_root (replacing one there), with an anchoring pytest.ini only on request. The directory must exist, in a container context within the shared work directory, else InvalidRequest. The shim finds the import root from its own place, in a container by the container's paths.

setup_files

setup_files(suite_root) -> Tuple[str, ...]

The setup file of a prepared generated suite, if present.

loaded_setup_files

loaded_setup_files(suite_root: Path, test_files: List[Path]) -> List[Path]

The conftest files pytest loads between the root and each test file, resolved on the host where the suite is stored, also in a container's work directory. A test file outside the root raises InvalidRequest.

project_pytest_config

project_pytest_config(executor, python: str, project_dir: Optional[str], cache: Optional[Dict[str, Optional[str]]] = None, *, flags: Sequence[str]) -> Optional[str]

The configuration file pytest reads for project_dir, by pytest's own order and rules, asked of the project's interpreter python with flags through executor with the plugins every run disables disabled, or None when pytest reads none. cache, when given, holds the answer per directory. Raises RuntimeError when the interpreter cannot import pytest or pytest names none for another reason.

isolation_args

isolation_args(config_path: Optional[str], read_file: Callable[[str], Optional[str]], suite_root: Optional[str] = None, *, execution_suite_root: Optional[str] = None) -> List[str]

pytest arguments isolating a staged suite: no cache provider and, for a project configuration config_path, its exact copy _PYTEST_CONFIG_COPY<suffix> in suite_root with -c, named under execution_suite_root (as a worker clone or container sees the root) when given. ValueError without a suite root, RuntimeError when it cannot be read or copied.

environment_dir

environment_dir(interpreter: str, root: str) -> Optional[str]

The project-relative directory (holding pyvenv.cfg or conda-meta) of interpreter's environment inside root, else None, compared as written. It is the run's runtime, not a project input, and stays out of project copies (a POSIX virtual environment's links cannot be copied).

langadapter.python.source_analysis

Static analysis and rewriting of Python test sources, running no project.

The operations parse with tree-sitter's Python grammar or ast, check with the calling interpreter's compiler and start no process. Python binds definitions in source order, so a later definition hides an earlier one of the same name and scope, and pytest cannot collect tests held only by the earlier one: the normalization removes those. The syntax repair judges each candidate with the caller's validator, which should use the project's interpreter. PythonAdapter holds the rewriting that also validates with the project's interpreter. The caller chooses the owner of a conflicting name.

RULE_VERSION module-attribute

RULE_VERSION = 'python-last-binding-v2'

The rule normalize_shadowed_definitions applies, which its records name.

SkipRemoval dataclass

SkipRemoval(source: str, count: int, parsed: bool, error: str = '')

Module-scope guards removed, or an explicit host-grammar parse error.

source instance-attribute

source: str

count instance-attribute

count: int

parsed instance-attribute

parsed: bool

error class-attribute instance-attribute

error: str = ''

SyntaxRepair dataclass

SyntaxRepair(source: Optional[str], status: str, repairs: int, validation: SourceValidation)

The repaired source, or None when repair or validation failed. status is valid, repaired, beyond_repair or validator_failed, validation the last validation (possibly an execution failure that judges no code) and repairs the edits applied before it.

source instance-attribute

source: Optional[str]

status instance-attribute

status: str

repairs instance-attribute

repairs: int

validation instance-attribute

validation: SourceValidation

normalize_shadowed_definitions

normalize_shadowed_definitions(source: str) -> SuiteNormalization

Remove definitions hidden by a later one of the same name in the same scope, recording each removed span and the rule version. A source that does not parse comes back unchanged with its parse error.

count_code_lines

count_code_lines(source: str) -> int

lizard's lines of code: the lines that hold code, without blank lines, comments and docstrings, counted without a parse tree, so also for incomplete source. It is not a statement count or a coverage denominator.

strip_module_level_skips

strip_module_level_skips(source: str) -> SkipRemoval

Remove each top-level expression or assignment statement that calls an importorskip attribute, or a skip attribute with allow_module_level=True. Guards inside a module-level if or try and calls in tests stay. The result is not validated.

merge_sources

merge_sources(first: str, second: str, *, separator: str) -> SourceResult

Merge two modules: the imports of both, deduplicated and hoisted, then the first body, the separator comment line and the second body. A statement both hold identically appears once when it only binds names and nothing run between the copies can change them. Parsed with tree-sitter and checked with the calling interpreter's compiler. Validation with the project's interpreter is the caller's. Raises InvalidRequest unless separator is one comment line.

collision_dependents

collision_dependents(source: str, binding: str, test_names: Iterable[str]) -> Tuple[str, ...]

The tests of test_names that depend on binding, also through its class methods, by the analysis collision rewriting uses. It does not prove a dynamic dependency. Raises InvalidRequest for an invalid source.

resolve_collisions

resolve_collisions(sources: Sequence[str], *, localize_autouse: bool = False, preference: Optional[Callable[[str, Tuple[int, ...]], Optional[int]]] = None) -> CollisionResolution

Rewrite static collisions between sources (left unmodified), leaving undecided conflicts intact. Each source is first cleared of definitions shadowed in its own scope, listed in dropped_defs, so a source without collisions can still be rewritten. preference(name, owners) gets the original source indices and names the owner of an unrenamable binding, or None to leave it unresolved. Another index raises InvalidRequest. Validate a rewrite with the interpreter it is delivered to.

salvage_syntax

salvage_syntax(source: str, validate: Callable[[str], SourceValidation]) -> SyntaxRepair

Repair source in at most 25 validation rounds, guided only by syntax errors: an "expected an indented block" error gets a pass body under the line it names, another error blanks its line. A validator execution failure stops the repair without a syntax verdict.