Skip to content
40 changes: 40 additions & 0 deletions docs/running.md
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,46 @@ instead of `--output`, `--job` and `--env-hash`. `collect --commands` prints a J
with each command's `id`, `job`, `file` and `keys`; it writes none when a command fails with `--strict-discovery`.
`--runtime-tags`, `--lock-file` and `--image` apply to every listed command.

#### Commands that run in a repository runner's environment

Some repositories don't call the framework from the CI job: the job calls the repository's own test runner, which
prepares a test environment and runs the framework inside it. A command names the runner environment it runs in
with `runner`:

```json
{"id": "vendor-py312", "job": "vendor 3.12", "env_hash": "f4cf61b462bb",
"argv": ["scripts/run-tests", "--venv", "f4cf61b462bb"],
"runner": {"suite": "vendor", "environment": "f4cf61b462bb"}}
```

- `suite` and `environment` name the environment as the runner lists it.
- `invocation` is the index of the environment's test command, from 0, when the environment runs more than one.
- `args` are the arguments the job passes through the runner to the test command. Optional.

Collection lists the runner's environments, finds the command the referenced one runs, and has the runner run
ddtest's worker in that command's place. The runner prepares the environment as it would for the job, and runs the
worker with the command's whole environment and the variables the runner sets for it. The worker probes the
interpreter that the command runs, and collects the command with `--ddtrace --collect-only` added to the
runner's `PYTEST_ADDOPTS`. The inventory records that interpreter's runtime and packages, and the identity and
skipping controls that the runner sets for the command, in place of ddtest's own. The command stays at `run` when:

- the runtime that the worker measures is not the version that the runner declares for the environment, whatever
`--runtime-tags` declare;
- the runner's command is a shell program, such as `pytest a && pytest b`, or doesn't run the framework;
- the runner sets a skipping control that turns skipping off, such as `_DD_CIVISIBILITY_ITR_PREVENT_TEST_SKIPPING=1`;
- `select --inventory` decides for another commit than the inventory's: the runner's own definitions, wherever the
repository keeps them, can change what the command collects, so a runner inventory decides only for its commit.

The worker finds the interpreter a `pytest` entry point runs inside the prepared environment, from the entry point's
own script, so the environment may not exist before collection. The runner gets no Datadog keys: the listing and
collection see a placeholder `DD_API_KEY` and no `DD_APP_KEY`.

Python repositories are supported whose `scripts/run-tests` defines a `TestRunner` with `environments` by suite,
each a dataclass with a `hash`, its `python` and its `runs`, and with `run_tests`, and that run it through
`scripts/uv-run-script`, as dd-trace-py does. ddtest checks that interface by loading the runner, not by reading its
source; a runner without it fails the listing, and its commands stay at `run`. The listing runs for at most two
minutes and may print at most 16 MiB.

### Collect in one place, select in another

Collection needs the test environment; the decision needs Datadog credentials.
Expand Down
8 changes: 8 additions & 0 deletions internal/ext/command_process_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,11 @@ func signalCommand(cmd *exec.Cmd, signal os.Signal) error {
}
return cmd.Process.Signal(signal)
}

// ConfigureProcessTree is a no-op where processes have no groups.
func ConfigureProcessTree(cmd *exec.Cmd) {}

// KillProcessTree kills cmd's process where processes have no groups.
func KillProcessTree(cmd *exec.Cmd) {
_ = signalCommand(cmd, os.Kill)
}
12 changes: 12 additions & 0 deletions internal/ext/command_process_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,15 @@ func signalCommand(cmd *exec.Cmd, signal os.Signal) error {
}
return nil
}

// ConfigureProcessTree starts cmd in its own process group, and cancels it by killing the whole group, so a timeout
// also stops the descendants it started.
func ConfigureProcessTree(cmd *exec.Cmd) {
configureCommandProcess(cmd)
}

// KillProcessTree kills what is left of cmd's process group once cmd returned, such as a descendant that kept running
// after cmd exited.
func KillProcessTree(cmd *exec.Cmd) {
_ = signalCommand(cmd, os.Kill)
}
8 changes: 8 additions & 0 deletions internal/ext/command_process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,11 @@ func signalCommand(cmd *exec.Cmd, _ os.Signal) error {
// instead of waiting through a grace period that cannot succeed.
return cmd.Process.Kill()
}

// ConfigureProcessTree is a no-op on Windows, where cancellation kills the process itself.
func ConfigureProcessTree(cmd *exec.Cmd) {}

// KillProcessTree kills cmd's process on Windows.
func KillProcessTree(cmd *exec.Cmd) {
_ = signalCommand(cmd, os.Kill)
}
10 changes: 9 additions & 1 deletion internal/platform/python.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const (
requiredPackageVersion = "4.11.0"
pytestAddOptsEnvVar = "PYTEST_ADDOPTS"
pytestDefaultAddOpts = "--ddtrace"
// pytestCollectOnlyAddOpts collects without running fixtures or tests.
pytestCollectOnlyAddOpts = "--collect-only"
)

type Python struct {
Expand Down Expand Up @@ -304,6 +306,12 @@ func (p *Python) RunEnv(options framework.RuntimeOptions) (map[string]string, er
return env, nil
}

// PythonDiscoveryAddOpts are the pytest options full discovery adds to PYTEST_ADDOPTS: the SDK plugin, and
// collection without running tests. A worker whose environment sets its own PYTEST_ADDOPTS adds them again.
func PythonDiscoveryAddOpts() string {
return pytestDefaultAddOpts + " " + pytestCollectOnlyAddOpts
}

func (p *Python) DiscoveryEnv(_ context.Context, kind framework.DiscoveryKind, options framework.RuntimeOptions) (map[string]string, error) {
switch kind {
case framework.FileDiscovery:
Expand All @@ -314,7 +322,7 @@ func (p *Python) DiscoveryEnv(_ context.Context, kind framework.DiscoveryKind, o
return nil, err
}
// Collect without running fixtures or tests, even when the SDK plugin is disabled.
env[pytestAddOptsEnvVar] = strings.TrimSpace(env[pytestAddOptsEnvVar] + " --collect-only")
env[pytestAddOptsEnvVar] = strings.TrimSpace(env[pytestAddOptsEnvVar] + " " + pytestCollectOnlyAddOpts)
return env, nil
default:
return nil, fmt.Errorf("unknown discovery kind: %d", kind)
Expand Down
66 changes: 48 additions & 18 deletions internal/platform/python_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
Expand Down Expand Up @@ -65,6 +66,31 @@ func majorMinorVersion(version string) string {

// CommandConfigurations uses the selected interpreter or explicit worker tags.
func (p *Python) CommandConfigurations(ctx context.Context, argv []string) (map[string]string, error) {
return p.commandConfigurations(func() (map[string]string, error) {
if len(argv) == 0 {
return nil, errNoInterpreter
}
interpreter, prefix, err := PythonProbeCommand(argv[0], argv[1:])
if err != nil {
return nil, fmt.Errorf("%w: %w", errNoInterpreter, err)
}
return p.CreateTagsMapForInterpreter(ctx, interpreter, prefix)
})
}

// MeasuredCommandConfigurations is CommandConfigurations for a command whose interpreter ddtest can't start itself,
// such as one a repository runner runs in its own environment: measured holds the runtime tags that interpreter
// reported where it collected.
func (p *Python) MeasuredCommandConfigurations(measured map[string]string) (map[string]string, error) {
return p.commandConfigurations(func() (map[string]string, error) { return measured, nil })
}

// errNoInterpreter is a measure's error when the command names no Python that ddtest can probe.
var errNoInterpreter = errors.New("supply complete --runtime-tags or a command that names its Python")

// commandConfigurations builds a command's configurations from explicit worker tags, or else from the runtime tags
// measure reports for the interpreter that collects. Explicit tags must name that interpreter's version.
func (p *Python) commandConfigurations(measure func() (map[string]string, error)) (map[string]string, error) {
var tags map[string]string
if settings.GetRuntimeTags() != "" {
var err error
Expand All @@ -73,15 +99,8 @@ func (p *Python) CommandConfigurations(ctx context.Context, argv []string) (map[
return nil, err
}
} else {
if len(argv) == 0 {
return nil, fmt.Errorf("supply complete --runtime-tags or a command that names its Python")
}
interpreter, prefix, err := PythonProbeCommand(argv[0], argv[1:])
if err != nil {
return nil, fmt.Errorf("supply complete --runtime-tags: %w", err)
}
tags, err = p.CreateTagsMapForInterpreter(ctx, interpreter, prefix)
if err != nil {
var err error
if tags, err = measure(); err != nil {
return nil, err
}
}
Expand All @@ -95,17 +114,15 @@ func (p *Python) CommandConfigurations(ctx context.Context, argv []string) (map[
configurations[key] = tags[key]
}
}
if settings.GetRuntimeTags() != "" && len(argv) > 0 {
if settings.GetRuntimeTags() != "" {
// The override names the workers' runtime, but collection runs the command's own Python. When their
// versions differ, the collected tests may not be the ones the workers run.
if interpreter, prefix, err := PythonProbeCommand(argv[0], argv[1:]); err == nil {
collecting, err := p.CreateTagsMapForInterpreter(ctx, interpreter, prefix)
if err != nil {
return nil, err
}
if majorMinorVersion(collecting["runtime.version"]) != majorMinorVersion(tags["runtime.version"]) {
return nil, fmt.Errorf("--runtime-tags declare Python %s, but the command collects with Python %s", tags["runtime.version"], collecting["runtime.version"])
}
collecting, err := measure()
if err != nil && !errors.Is(err, errNoInterpreter) {
return nil, err
}
if err == nil && majorMinorVersion(collecting["runtime.version"]) != majorMinorVersion(tags["runtime.version"]) {
return nil, fmt.Errorf("--runtime-tags declare Python %s, but the command collects with Python %s", tags["runtime.version"], collecting["runtime.version"])
}
}
customTags := os.Getenv("DD_TAGS")
Expand Down Expand Up @@ -156,6 +173,11 @@ func (p *Python) CommandPackages(ctx context.Context, argv []string, framework,
if err != nil {
return CommandPackages{}, err
}
return ParseCommandPackages(data)
}

// ParseCommandPackages reads the packages the packages probe wrote.
func ParseCommandPackages(data []byte) (CommandPackages, error) {
var packages CommandPackages
if err := json.Unmarshal(data, &packages); err != nil {
return CommandPackages{}, fmt.Errorf("parse installed packages: %w", err)
Expand All @@ -166,6 +188,14 @@ func (p *Python) CommandPackages(ctx context.Context, argv []string, framework,
return packages, nil
}

// PythonProbeScripts are the scripts that probe a Python: the one that writes its runtime tags to the file its
// first argument names, and the one that writes its packages to its first argument's file, given a framework's
// plugin entry point group and the framework as the next two. A worker that runs inside an environment ddtest can't
// start itself, such as a repository runner's, runs them there.
func PythonProbeScripts() (runtimeTags, packages string) {
return pythonEnvScript, pythonPackagesScript
}

// ResetCommandEnvironment reads the framework's base environment, such as PYTEST_ADDOPTS, from the process again.
// Collection calls it once a command's environment is applied, and again once it is restored.
func (p *Python) ResetCommandEnvironment() {
Expand Down
41 changes: 41 additions & 0 deletions internal/platform/python_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,44 @@ func TestPythonPackagesScriptListsDistributionsAndPlugins(t *testing.T) {
require.Contains(t, distribution, "==")
}
}

func TestPythonEnvironmentProbeCommand(t *testing.T) {
t.Setenv("PATH", t.TempDir())
for _, entryPoint := range []string{"pytest", ".venv/bin/pytest"} {
interpreter, _, resolveInside, err := PythonEnvironmentProbeCommand(entryPoint, []string{"tests"})
require.NoError(t, err, "an entry point that doesn't exist yet is resolved inside the environment")
require.Empty(t, interpreter)
require.Equal(t, entryPoint, resolveInside)
}
for _, tc := range []struct {
argv []string
want []string
}{
{[]string{"python3.12", "-X", "dev", "-m", "pytest"}, []string{"python3.12", "-X", "dev"}},
{[]string{"uv", "run", "pytest"}, []string{"uv", "run", "--no-sync", "python"}},
} {
interpreter, prefix, entryPoint, err := PythonEnvironmentProbeCommand(tc.argv[0], tc.argv[1:])
require.NoError(t, err, tc.argv)
require.Empty(t, entryPoint)
require.Equal(t, tc.want, append([]string{interpreter}, prefix...))
}
_, _, _, err := PythonEnvironmentProbeCommand("tox", []string{"-e", "py312"})
require.Error(t, err)
}

func TestPythonMeasuredCommandConfigurations(t *testing.T) {
viper.Reset()
settings.Init()
t.Cleanup(func() { viper.Reset(); settings.Init() })
t.Setenv("_CI_DD_TAGS", "test.configuration.env_hash:abc")
measured := map[string]string{"runtime.name": "CPython", "runtime.version": "3.12.9", "os.platform": "Linux", "os.architecture": "x86_64", "os.version": "6.1"}
tags, err := NewPython().MeasuredCommandConfigurations(measured)
require.NoError(t, err)
require.Equal(t, "3.12.9", tags["runtime.version"])
require.Equal(t, "abc", tags["test.configuration.env_hash"])

viper.Set("runtime_tags", `{"runtime.name":"CPython","runtime.version":"3.13.0","os.platform":"Linux","os.architecture":"x86_64","os.version":"worker"}`)
settings.Init()
_, err = NewPython().MeasuredCommandConfigurations(measured)
require.ErrorContains(t, err, "--runtime-tags declare Python 3.13.0, but the command collects with Python 3.12.9")
}
12 changes: 12 additions & 0 deletions internal/platform/python_launchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,18 @@ func PythonProbeCommand(command string, args []string) (string, []string, error)
return "", nil, fmt.Errorf("cannot identify a Python interpreter in %q", command)
}

// PythonEnvironmentProbeCommand is PythonProbeCommand for a command that runs inside an environment ddtest doesn't
// prepare itself, such as a repository runner's. A pytest entry point there may not exist before the environment is
// prepared, and runs the interpreter its own script names, so entryPoint returns it for the environment to resolve
// instead of an interpreter.
func PythonEnvironmentProbeCommand(command string, args []string) (interpreter string, prefix []string, entryPoint string, err error) {
if strings.TrimSuffix(filepath.Base(command), ".exe") == "pytest" {
return "", nil, command, nil
}
interpreter, prefix, err = PythonProbeCommand(command, args)
return interpreter, prefix, "", err
}

// pytestEntryPointPython returns the Python a pytest entry point runs. On Windows the launcher is an executable next
// to its environment's python.exe. Elsewhere the script names its interpreter on its #! line, which can differ from
// the Python next to it, for example when the entry point links to another environment's pytest.
Expand Down
Loading
Loading