diff --git a/docs/running.md b/docs/running.md index ef88b338a..43b9f6a17 100644 --- a/docs/running.md +++ b/docs/running.md @@ -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. diff --git a/internal/ext/command_process_other.go b/internal/ext/command_process_other.go index 09b42129f..4c8c48619 100644 --- a/internal/ext/command_process_other.go +++ b/internal/ext/command_process_other.go @@ -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) +} diff --git a/internal/ext/command_process_unix.go b/internal/ext/command_process_unix.go index 1b852f52b..b89d879a4 100644 --- a/internal/ext/command_process_unix.go +++ b/internal/ext/command_process_unix.go @@ -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) +} diff --git a/internal/ext/command_process_windows.go b/internal/ext/command_process_windows.go index dc3b1c4af..63975b876 100644 --- a/internal/ext/command_process_windows.go +++ b/internal/ext/command_process_windows.go @@ -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) +} diff --git a/internal/platform/python.go b/internal/platform/python.go index d44977264..8c324e4c5 100644 --- a/internal/platform/python.go +++ b/internal/platform/python.go @@ -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 { @@ -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: @@ -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) diff --git a/internal/platform/python_command.go b/internal/platform/python_command.go index 69a9c4353..d19754ba7 100644 --- a/internal/platform/python_command.go +++ b/internal/platform/python_command.go @@ -4,6 +4,7 @@ import ( "context" _ "embed" "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -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 @@ -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 } } @@ -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") @@ -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) @@ -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() { diff --git a/internal/platform/python_command_test.go b/internal/platform/python_command_test.go index 50cd84951..c4ca8b120 100644 --- a/internal/platform/python_command_test.go +++ b/internal/platform/python_command_test.go @@ -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") +} diff --git a/internal/platform/python_launchers.go b/internal/platform/python_launchers.go index 2f405986d..6912ce29f 100644 --- a/internal/platform/python_launchers.go +++ b/internal/platform/python_launchers.go @@ -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. diff --git a/internal/selection/collect.go b/internal/selection/collect.go index 97d18ef47..c5f5e643d 100644 --- a/internal/selection/collect.go +++ b/internal/selection/collect.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "slices" + "strconv" "strings" "time" @@ -29,13 +30,15 @@ import ( // CommandPlatform is what a platform provides so select can collect its test commands: the arguments a command // passes to a framework, the environment name and skipping level the command's workers report, the runtime tags -// and installed packages of the interpreter the command runs, and the lock files a job installs from. Python -// implements it; another platform joins select by implementing it. +// and installed packages of the interpreter the command runs, or the configurations of the runtime tags measured +// where a repository runner runs it, and the lock files a job installs from. Python implements it; another platform +// joins select by implementing it. type CommandPlatform interface { platform.Platform CommandEnvironmentName() string CommandTestSkippingLevel(override settings.TestSkippingLevel) settings.TestSkippingLevel CommandConfigurations(ctx context.Context, argv []string) (map[string]string, error) + MeasuredCommandConfigurations(measured map[string]string) (map[string]string, error) CommandPackages(ctx context.Context, argv []string, framework, pluginGroup string) (platform.CommandPackages, error) CommandLockFiles() []string ResetCommandEnvironment() @@ -134,8 +137,18 @@ func (s *Selector) collectCommand(ctx context.Context, options Options, command Variables: identity, Git: checkout.Tags}, Errors: []string{}, } + inventory.Identity.Runner = command.Runner frameworkArgs, runsFramework := commandPlatform.FrameworkArguments(fw.Name(), argv) - if inventory.Identity.Cwd != "." { + if command.Runner != nil { + if inventory.Identity.Cwd != "." { + inventory.Errors = append(inventory.Errors, "collection supports commands that run at the repository root only") + } else { + inventory.Errors = append(inventory.Errors, s.collectInRunner(ctx, &inventory, commandPlatform, collector, *command.Runner, mode, checkout.RepositoryURL)...) + } + if settings.GetStrictDiscovery() && len(inventory.Errors) > 0 { + return Inventory{}, fmt.Errorf("%s", strings.Join(inventory.Errors, "; ")) + } + } else if inventory.Identity.Cwd != "." { inventory.Errors = append(inventory.Errors, "collection supports commands that run at the repository root only") } else if !runsFramework { inventory.Errors = append(inventory.Errors, "command planning requires a "+fw.Name()+" invocation") @@ -181,6 +194,61 @@ func (s *Selector) collectCommand(ctx context.Context, options Options, command return inventory, ctx.Err() } +// collectInRunner collects a command that runs its tests in a repository runner's environment. The runner prepares +// the environment and runs ddtest's worker there, which reports what the command runs with: its interpreter's +// runtime and packages, and the identity and skipping controls its environment sets, which the inventory records +// instead of ddtest's own. It returns the collection's errors. +func (s *Selector) collectInRunner(ctx context.Context, inventory *Inventory, commandPlatform CommandPlatform, collector CommandFramework, reference RunnerReference, mode settings.TestSkippingLevel, repositoryURL string) []string { + runner, err := s.runner() + if err != nil { + return []string{err.Error()} + } + invocation, err := runner.resolve(ctx, reference) + if err != nil { + return []string{err.Error()} + } + frameworkArgs, runsFramework := commandPlatform.FrameworkArguments(s.framework.Name(), invocation.Argv) + if !runsFramework { + return []string{"command planning requires a " + s.framework.Name() + " invocation; the runner runs " + strconv.Quote(invocation.Command)} + } + // The worker reports the identity variables and the framework options the runner gives the command. + variables := append(slices.Clone(inventoryIdentityVariables), "PYTEST_ADDOPTS") + collection, err := runner.collect(ctx, invocation, s.framework.Name(), collector.CommandPluginGroup(), variables) + if err != nil { + return []string{"full discovery failed: " + err.Error()} + } + inventory.Inputs.VenvSHA256 = sha256Hex([]byte(strings.Join(collection.Packages.Distributions, "\n"))) + inventory.Inputs.Plugins = collection.Packages.Plugins + // The measured runtime is checked against the environment before any runtime tags name the workers' runtime. + if measured := collection.RuntimeTags["runtime.version"]; !runnerVersionMatches(measured, invocation.RuntimeVersion) { + return []string{fmt.Sprintf("the runner environment declares runtime %s, but its command collects with %s %s", invocation.RuntimeVersion, collection.RuntimeTags["runtime.name"], measured)} + } + var problems []string + withExactEnvironment(variables, collection.Variables, func() { + identity := collectionIdentity() + inventory.Datadog.Variables = identity + inventory.Datadog.Service = runmetadata.ResolveServiceName(repositoryURL) + inventory.Datadog.Env = commandPlatform.CommandEnvironmentName() + inventory.Datadog.TestLevel = commandPlatform.CommandTestSkippingLevel(mode).String() + inventory.Identity.PytestConfig = fileDigest(collector.CommandConfigFile(append(inheritedFrameworkArgs(), frameworkArgs...))) + if reason := suitePlanningPolicy(identity); reason != "" { + problems = append(problems, reason) + } + tags, err := commandPlatform.MeasuredCommandConfigurations(collection.RuntimeTags) + if err != nil { + problems = append(problems, "runtime configuration unavailable: "+err.Error()) + } else { + inventory.Inputs.Configurations = tags + } + }) + inventory.Tests = collection.Tests + if len(collection.Tests) == 0 { + problems = append(problems, "full discovery returned no tests") + } + inventory.UnskippableFiles = unskippableFiles(s.framework, candidateTestFiles(collection.Tests)) + return problems +} + // inheritedFrameworkArgs are the arguments pytest reads from PYTEST_ADDOPTS before the command's own. func inheritedFrameworkArgs() []string { args, err := shellquote.Split(os.Getenv("PYTEST_ADDOPTS")) diff --git a/internal/selection/commands.go b/internal/selection/commands.go index d7ccf05c9..3fc667e35 100644 --- a/internal/selection/commands.go +++ b/internal/selection/commands.go @@ -24,7 +24,8 @@ type CommandsFile struct { } // CallerCommand is one test command of a CI job, as the job runs it. Env holds the variables the job sets for the -// command, on top of ddtest's own environment. +// command, on top of ddtest's own environment. Runner names the repository runner environment the command runs its +// tests in, when the job runs them through the repository's own runner instead of calling the framework itself. type CallerCommand struct { ID string `json:"id"` Job string `json:"job"` @@ -32,6 +33,18 @@ type CallerCommand struct { Argv []string `json:"argv"` Cwd string `json:"cwd"` Env map[string]string `json:"env"` + Runner *RunnerReference `json:"runner,omitempty"` +} + +// RunnerReference names one test invocation of a repository runner: an environment of one of its suites, as the +// runner lists them. Collection runs it inside that environment, which the runner prepares itself. +type RunnerReference struct { + Suite string `json:"suite"` + Environment string `json:"environment"` + // Invocation is the index of the environment's test command, when it runs more than one. + Invocation *int `json:"invocation,omitempty"` + // Args are the arguments the job passes through the runner to the test command. + Args []string `json:"args,omitempty"` } // commandIDPattern keeps a command ID usable as a file name. @@ -86,6 +99,14 @@ func ReadCommands(path string) ([]CallerCommand, error) { } else if !filepath.IsLocal(command.Cwd) && filepath.Clean(command.Cwd) != "." { return nil, fmt.Errorf("%s: cwd %q must be a path inside the repository", where, command.Cwd) } + if runner := command.Runner; runner != nil { + if strings.TrimSpace(runner.Suite) == "" || strings.TrimSpace(runner.Environment) == "" { + return nil, fmt.Errorf("%s: runner needs a suite and an environment", where) + } + if runner.Invocation != nil && *runner.Invocation < 0 { + return nil, fmt.Errorf("%s: runner invocation %d is no index", where, *runner.Invocation) + } + } for _, name := range slices.Sorted(maps.Keys(command.Env)) { if !variableNamePattern.MatchString(name) { return nil, fmt.Errorf("%s: env name %q is not a variable name", where, name) @@ -128,6 +149,36 @@ func withCommandEnvironment(env map[string]string, fn func() error) error { return fn() } +// withExactEnvironment runs fn with the process environment's names set to values, and unset where values has +// none, and with settings read again. It restores the process environment and settings afterwards. +func withExactEnvironment(names []string, values map[string]string, fn func()) { + previous := map[string]*string{} + for _, name := range names { + if old, exists := os.LookupEnv(name); exists { + previous[name] = &old + } else { + previous[name] = nil + } + if value, exists := values[name]; exists { + _ = os.Setenv(name, value) + } else { + _ = os.Unsetenv(name) + } + } + settings.Init() + defer func() { + for name, value := range previous { + if value == nil { + _ = os.Unsetenv(name) + } else { + _ = os.Setenv(name, *value) + } + } + settings.Init() + }() + fn() +} + // overlayEnviron is environ with env's values in place of its own. func overlayEnviron(environ []string, env map[string]string) []string { if len(env) == 0 { diff --git a/internal/selection/decide.go b/internal/selection/decide.go index 8dae3af4b..0cb2e33a0 100644 --- a/internal/selection/decide.go +++ b/internal/selection/decide.go @@ -78,7 +78,10 @@ func decideInventories(ctx context.Context, inventories []Inventory, checkout bo job.Variables = workerVariables(collected) command := catalogCommand(collected) if command.Unresolved == "" && !strings.EqualFold(inventory.Identity.Commit, commit) { - if file := collectionChange(inventory, changed); file != "" { + // A runner's own definitions, wherever the repository keeps them, decide what its command collects. + if inventory.Identity.Runner != nil { + command.Unresolved = "inventory is for commit " + inventory.Identity.Commit + ", and a repository runner's definitions can change what its command collects" + } else if file := collectionChange(inventory, changed); file != "" { command.Unresolved = "inventory is for commit " + inventory.Identity.Commit + ", and " + file + " changed since, which can change the collected tests" } } diff --git a/internal/selection/inventory.go b/internal/selection/inventory.go index 3fbbd67ea..a2d3a9e52 100644 --- a/internal/selection/inventory.go +++ b/internal/selection/inventory.go @@ -67,7 +67,8 @@ type Inventory struct { } // InventoryIdentity is the command as CI runs it: the repository, the commit, the CI job and its environment hash, -// the unchanged command line and the framework configuration file it reads. +// the unchanged command line, the framework configuration file it reads, and the repository runner environment it +// runs its tests in. type InventoryIdentity struct { Repo string `json:"repo"` Commit string `json:"commit"` @@ -76,6 +77,8 @@ type InventoryIdentity struct { Argv []string `json:"argv"` Cwd string `json:"cwd"` PytestConfig InventoryFileDigest `json:"pytest_config"` + // Runner is the repository runner environment the command runs its tests in, or nil when it runs them itself. + Runner *RunnerReference `json:"runner,omitempty"` } // InventoryFileDigest names a file and the sha256 of its bytes. Both are empty when there is no file. diff --git a/internal/selection/python_runner.go b/internal/selection/python_runner.go new file mode 100644 index 000000000..8e12138fe --- /dev/null +++ b/internal/selection/python_runner.go @@ -0,0 +1,327 @@ +package selection + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + _ "embed" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "maps" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/DataDog/ddtest/internal/constants" + "github.com/DataDog/ddtest/internal/discovery" + "github.com/DataDog/ddtest/internal/ext" + "github.com/DataDog/ddtest/internal/platform" + "github.com/kballard/go-shellquote" +) + +//go:embed scripts/python_runner.py +var pythonRunnerModule string + +//go:embed scripts/python_runner_catalog.py +var pythonRunnerCatalog string + +//go:embed scripts/python_runner_collection.py +var pythonRunnerCollection string + +//go:embed scripts/python_runner_worker.py +var pythonRunnerWorker string + +const ( + // pythonRunnerScript is the repository's test runner, which pythonRunnerLauncher runs with the dependencies its + // inline script metadata declares. + pythonRunnerScript = "scripts/run-tests" + pythonRunnerLauncher = "scripts/uv-run-script" + // pythonRunnerModuleName is the name ddtest's scripts import the runner loader as. + pythonRunnerModuleName = "ddtest_python_runner" + // pythonRunnerUnsupported is the exit status of a listing that found no runner interface it knows. + pythonRunnerUnsupported = 3 +) + +// The listing's bounds: its time, what it may print, and how long to wait for output pipes a descendant keeps open +// after the listing exits. +var ( + pythonRunnerListingTimeout = 2 * time.Minute + pythonRunnerListingLimit = 16 << 20 + pythonRunnerDiagnosticLimit = 64 << 10 + pythonRunnerListingWaitDelay = 5 * time.Second +) + +// pythonRunner is a Python repository's own test runner, scripts/run-tests: it declares test environments by +// suite, each with its Python and the commands it runs, and prepares an environment before it runs its commands. +// ddtest lists the environments through the runner's TestRunner, and collects a command by having run_tests run +// ddtest's worker in its place. +type pythonRunner struct { + executor ext.CommandExecutor + // listings are the runner's listings by the process environment they were listed in, since the runner's + // environments can depend on it. + listings map[string]pythonRunnerListing +} + +func newPythonRunner() *pythonRunner { + return &pythonRunner{executor: &ext.DefaultCommandExecutor{}, listings: map[string]pythonRunnerListing{}} +} + +// pythonRunnerListing is what the runner lists: its suites, their environments, and the commands each runs. +type pythonRunnerListing struct { + Suites []struct { + Name string `json:"name"` + Environments []struct { + Hash string `json:"hash"` + Python string `json:"python"` + Invocations []struct { + Command string `json:"command"` + } `json:"invocations"` + } `json:"environments"` + } `json:"suites"` +} + +func (r *pythonRunner) resolve(ctx context.Context, reference RunnerReference) (runnerInvocation, error) { + listing, err := r.listing(ctx) + if err != nil { + return runnerInvocation{}, err + } + for _, suite := range listing.Suites { + if suite.Name != reference.Suite { + continue + } + for _, environment := range suite.Environments { + if environment.Hash != reference.Environment { + continue + } + index := 0 + switch { + case reference.Invocation != nil: + index = *reference.Invocation + case len(environment.Invocations) != 1: + return runnerInvocation{}, fmt.Errorf("runner environment %s runs %d commands; name one with runner.invocation", reference.Environment, len(environment.Invocations)) + } + if index >= len(environment.Invocations) { + return runnerInvocation{}, fmt.Errorf("runner environment %s has no invocation %d", reference.Environment, index) + } + // The runner puts the arguments the job passes through it in place of {cmdargs}. + command := strings.ReplaceAll(environment.Invocations[index].Command, "{cmdargs}", shellquote.Join(reference.Args...)) + argv, ok := commandWords(command) + if !ok { + return runnerInvocation{}, fmt.Errorf("runner command %q is a shell program; collection supports one framework command", command) + } + return runnerInvocation{Reference: reference, Command: command, Argv: argv, RuntimeVersion: environment.Python}, nil + } + return runnerInvocation{}, fmt.Errorf("runner suite %q has no environment %s", reference.Suite, reference.Environment) + } + return runnerInvocation{}, fmt.Errorf("runner has no suite %q", reference.Suite) +} + +// listing lists the runner's environments, once per process environment. +func (r *pythonRunner) listing(ctx context.Context) (pythonRunnerListing, error) { + environ := os.Environ() + slices.Sort(environ) + key := sha256.Sum256([]byte(strings.Join(environ, "\x00"))) + if listing, ok := r.listings[hex.EncodeToString(key[:])]; ok { + return listing, nil + } + directory, launcher, err := pythonRunnerDirectory(map[string]string{"catalog.py": pythonRunnerCatalog}) + if err != nil { + return pythonRunnerListing{}, err + } + defer func() { _ = os.RemoveAll(directory) }() + bounded, cancel := context.WithTimeout(ctx, pythonRunnerListingTimeout) + defer cancel() + // no-dd-sa:go-security/command-injection + cmd := exec.CommandContext(bounded, launcher, filepath.Join(directory, "catalog.py")) + output, diagnostic := &cappedOutput{limit: pythonRunnerListingLimit}, &cappedOutput{limit: pythonRunnerDiagnosticLimit} + cmd.Stdout, cmd.Stderr = output, diagnostic + // The runner is repository code, which never gets Datadog keys; listing needs none. + cmd.Env = overlayEnviron(slices.DeleteFunc(os.Environ(), func(entry string) bool { return strings.HasPrefix(entry, "DD_APP_KEY=") }), + map[string]string{"DD_API_KEY": discovery.BaseEnv()["DD_API_KEY"]}) + // A descendant that keeps the output pipes open must not hold the listing past its exit or its timeout, nor + // outlive it: the listing runs in its own process group, which a timeout kills, and what is left of it is killed + // once the listing returns. + cmd.WaitDelay = pythonRunnerListingWaitDelay + ext.ConfigureProcessTree(cmd) + err = cmd.Run() + ext.KillProcessTree(cmd) + if err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && exit.ExitCode() == pythonRunnerUnsupported { + return pythonRunnerListing{}, fmt.Errorf("runner listing unavailable: %s", strings.TrimSpace(diagnostic.String())) + } + return pythonRunnerListing{}, fmt.Errorf("runner listing unavailable: %w: %s", err, lastLines(diagnostic.String(), 20)) + } + if output.truncated { + return pythonRunnerListing{}, fmt.Errorf("runner listing exceeds %d bytes", pythonRunnerListingLimit) + } + var listing pythonRunnerListing + if err := json.Unmarshal(output.Bytes(), &listing); err != nil { + return pythonRunnerListing{}, fmt.Errorf("runner listing unavailable: %w", err) + } + r.listings[hex.EncodeToString(key[:])] = listing + return listing, nil +} + +// pythonRunnerSelection is what the collection script and the worker read. +type pythonRunnerSelection struct { + Suite string `json:"suite"` + Environment string `json:"environment"` + Invocation int `json:"invocation"` + WorkerCommand string `json:"worker_command"` + DiscoveryVariables []string `json:"discovery_variables"` + Command string `json:"command"` + Probe []string `json:"probe"` + EntryPoint string `json:"entry_point"` + RuntimeScript string `json:"runtime_script"` + RuntimeFile string `json:"runtime_file"` + PackagesScript string `json:"packages_script"` + PackagesFile string `json:"packages_file"` + PluginGroup string `json:"plugin_group"` + Framework string `json:"framework"` + Variables []string `json:"variables"` + VariablesFile string `json:"variables_file"` + AddOpts string `json:"addopts"` +} + +func (r *pythonRunner) collect(ctx context.Context, invocation runnerInvocation, framework, pluginGroup string, variables []string) (runnerCollection, error) { + // The worker probes the Python that runs the command, inside the runner's environment, where it also finds the + // interpreter a pytest entry point runs. + interpreter, prefix, entryPoint, err := platform.PythonEnvironmentProbeCommand(invocation.Argv[0], invocation.Argv[1:]) + if err != nil { + return runnerCollection{}, err + } + var probe []string + launch := []string{"python3"} + if entryPoint == "" { + probe = append([]string{interpreter}, prefix...) + launch = probe + } + directory, launcher, err := pythonRunnerDirectory(map[string]string{"collect.py": pythonRunnerCollection, "worker.py": pythonRunnerWorker}) + if err != nil { + return runnerCollection{}, err + } + defer func() { _ = os.RemoveAll(directory) }() + // The paths are relative to the repository root, where the runner runs its commands, also inside a container + // that mounts the repository elsewhere. + file := func(name string) string { return filepath.ToSlash(filepath.Join(directory, name)) } + runtimeScript, packagesScript := platform.PythonProbeScripts() + selection := pythonRunnerSelection{ + Suite: invocation.Reference.Suite, Environment: invocation.Reference.Environment, + WorkerCommand: shellquote.Join(append(slices.Clone(launch), file("worker.py"), file("selection.json"))...), + DiscoveryVariables: slices.Sorted(maps.Keys(discovery.BaseEnv())), + Command: invocation.Command, Probe: probe, EntryPoint: entryPoint, + RuntimeScript: runtimeScript, RuntimeFile: file("runtime.json"), + PackagesScript: packagesScript, PackagesFile: file("packages.json"), PluginGroup: pluginGroup, Framework: framework, + Variables: variables, VariablesFile: file("variables.json"), AddOpts: platform.PythonDiscoveryAddOpts(), + } + if invocation.Reference.Invocation != nil { + selection.Invocation = *invocation.Reference.Invocation + } + data, err := json.Marshal(selection) + if err != nil { + return runnerCollection{}, err + } + if err := os.WriteFile(file("selection.json"), data, 0600); err != nil { + return runnerCollection{}, err + } + // The runner runs with the command's whole environment, but no Datadog keys; discovery adds only its own + // variables, with a placeholder key, which the collection script passes on to the worker. + tests, err := discovery.DiscoverCommand(ctx, r.executor, launcher, []string{file("collect.py"), file("selection.json")}, + map[string]string{"DD_APP_KEY": ext.UnsetEnvironment}) + if err != nil { + return runnerCollection{}, err + } + collection := runnerCollection{Tests: tests} + if err := readJSONFile(file("runtime.json"), &collection.RuntimeTags); err != nil { + return runnerCollection{}, fmt.Errorf("read the worker's runtime tags: %w", err) + } + if err := readJSONFile(file("variables.json"), &collection.Variables); err != nil { + return runnerCollection{}, fmt.Errorf("read the worker's variables: %w", err) + } + packages, err := os.ReadFile(file("packages.json")) + if err != nil { + return runnerCollection{}, fmt.Errorf("read the worker's packages: %w", err) + } + if collection.Packages, err = platform.ParseCommandPackages(packages); err != nil { + return runnerCollection{}, err + } + return collection, ctx.Err() +} + +// pythonRunnerDirectory writes ddtest's runner scripts to a new directory inside the repository, where a runner +// that runs its commands in a container still finds them, and returns it with the runner's launcher. Each script +// starts with the runner's own inline script metadata, so it runs with the dependencies the runner loads with. +func pythonRunnerDirectory(scripts map[string]string) (string, string, error) { + launcher := filepath.Join(".", pythonRunnerLauncher) + source, err := os.ReadFile(pythonRunnerScript) + if err != nil { + return "", "", fmt.Errorf("runner listing unavailable: %w", err) + } + if info, err := os.Stat(launcher); err != nil || info.IsDir() { + return "", "", fmt.Errorf("runner listing unavailable: %s runs with %s, which is missing", pythonRunnerScript, pythonRunnerLauncher) + } + if err := os.MkdirAll(constants.PlanDirectory, 0755); err != nil { + return "", "", err + } + directory, err := os.MkdirTemp(constants.PlanDirectory, "runner-") + if err != nil { + return "", "", err + } + metadata := inlineScriptMetadata(source) + scripts[pythonRunnerModuleName+".py"] = pythonRunnerModule + for name, script := range scripts { + if strings.HasSuffix(name, ".py") && name != pythonRunnerModuleName+".py" && name != "worker.py" { + script = metadata + script + } + if err := os.WriteFile(filepath.Join(directory, name), []byte(script), 0600); err != nil { + _ = os.RemoveAll(directory) + return "", "", err + } + } + return directory, launcher, nil +} + +// inlineScriptMetadata returns a script's inline metadata block, the `# /// script` lines that declare the Python +// and dependencies it runs with, or "" when it has none. +func inlineScriptMetadata(source []byte) string { + var block strings.Builder + inside := false + scanner := bufio.NewScanner(bytes.NewReader(source)) + for scanner.Scan() { + line := scanner.Text() + switch { + case !inside && strings.TrimRight(line, " ") == "# /// script": + inside = true + case inside && strings.TrimRight(line, " ") == "# ///": + block.WriteString(line + "\n") + return block.String() + case inside && line != "#" && !strings.HasPrefix(line, "# "): + return "" + } + if inside { + block.WriteString(line + "\n") + } + } + return "" +} + +func readJSONFile(path string, value any) error { + data, err := os.ReadFile(path) + if err != nil { + return err + } + return json.Unmarshal(data, value) +} + +// lastLines keeps the last n lines of a command's diagnostic output. +func lastLines(output string, n int) string { + lines := strings.Split(strings.TrimSpace(output), "\n") + return strings.Join(lines[max(0, len(lines)-n):], "\n") +} diff --git a/internal/selection/python_runner_test.go b/internal/selection/python_runner_test.go new file mode 100644 index 000000000..2376d5d39 --- /dev/null +++ b/internal/selection/python_runner_test.go @@ -0,0 +1,425 @@ +package selection + +import ( + "bytes" + "encoding/json" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/DataDog/ddtest/internal/settings" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" +) + +// fakePythonRunner is a repository test runner with the interface of scripts/run-tests: test environments by suite, +// each a dataclass with its Python and runs, and run_tests, which runs each run's command with its env in the +// environment's bin directory, as the runner would after preparing it. +const fakePythonRunner = `#!/usr/bin/env scripts/uv-run-script +# /// script +# requires-python = ">=3.8" +# dependencies = [] +# /// +import dataclasses +import os +import subprocess + + +@dataclasses.dataclass(frozen=True) +class TestRun: + command: str + env: tuple = () + + @property + def environment(self): + return dict(self.env) + + +@dataclasses.dataclass(frozen=True) +class TestEnvironment: + suite: str + python: str + runs: tuple + + @property + def hash(self): + return "env-" + self.suite + + +class TestRunner: + def __init__(self): + print("loading the test runner") + with open("listings.txt", "a") as stream: + stream.write("listed\n") + with open("api-keys.txt", "a") as stream: + stream.write(os.environ.get("DD_API_KEY", "unset") + "\n") + if "DD_APP_KEY" in os.environ: + raise SystemExit("the runner got DD_APP_KEY") + python = os.environ["FAKE_RUNNER_PYTHON"] + run_env = ( + ("PYTEST_ADDOPTS", "-p no:cacheprovider"), + ("_CI_DD_TAGS", "test.configuration.env_hash:env-unit"), + ("_DD_CIVISIBILITY_ITR_PREVENT_TEST_SKIPPING", "0"), + ) + self.environments = { + "unit": [TestEnvironment("unit", python, (TestRun("pytest {cmdargs} tests/test_actual.py", run_env),))], + "guarded": [TestEnvironment("guarded", python, ( + TestRun("pytest tests/test_actual.py", (("_DD_CIVISIBILITY_ITR_PREVENT_TEST_SKIPPING", "1"),)),))], + "multi": [TestEnvironment("multi", python, (TestRun("pytest tests/a"), TestRun("pytest tests/test_actual.py")))], + "shell": [TestEnvironment("shell", python, (TestRun("pytest tests/a && pytest tests/b"),))], + "script": [TestEnvironment("script", python, (TestRun("python tests/smoke.py"),))], + "old": [TestEnvironment("old", "2.7", (TestRun("pytest tests/test_actual.py"),))], + "service": [TestEnvironment("service", python, ( + TestRun("pytest tests/test_actual.py", (("DD_SERVICE", "runner-service"),)),))], + } + + def run_tests(self, environments, test_args=None): + for environment in environments: + for run in environment.runs: + env = dict(os.environ) + env.update(run.environment) + env["PATH"] = os.path.abspath("env/bin") + os.pathsep + env["PATH"] + if subprocess.run(["bash", "-c", run.command], env=env).returncode != 0: + return False + return True +` + +// fakeEnvironmentPython is the environment's python on PATH: the host's, recording each call. +const fakeEnvironmentPython = "#!/bin/sh\nprintf '%s\\n' \"$1\" >> python-calls.txt\nexec python3 \"$@\"\n" + +// fakeEntryPointPython is the interpreter the environment's pytest names, which isn't the python on PATH. +const fakeEntryPointPython = "#!/bin/sh\nprintf '%s\\n' \"$1\" >> entry-point-calls.txt\nexec python3 \"$@\"\n" + +// fakeEnvironmentPytest is the environment's pytest entry point, in the form uv writes for a relocatable +// environment. It records what it collects with and reports one test. +const fakeEnvironmentPytest = `#!/bin/sh +'''exec' "$(dirname -- "$(realpath -- "$0")")"/'python-entry' "$0" "$@" +' ''' +import os +import sys + +with open("addopts.txt", "w") as stream: + stream.write(os.environ.get("PYTEST_ADDOPTS", "") + "\n") +with open("command-flag.txt", "w") as stream: + stream.write(os.environ.get("COMMAND_FLAG", "unset") + "\n") +with open("arguments.txt", "w") as stream: + stream.write("\n".join(sys.argv[1:]) + "\n") +with open("identities.json") as source, open(os.environ["DD_TEST_OPTIMIZATION_DISCOVERY_FILE"], "w") as report: + report.write(source.read()) +` + +// hostPythonVersion is the major and minor version of the python3 the fake runner's environment runs. +func hostPythonVersion(t *testing.T) string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("requires a POSIX shell") + } + for _, tool := range []string{"python3", "bash"} { + if _, err := exec.LookPath(tool); err != nil { + t.Skipf("requires %s", tool) + } + } + output, err := exec.Command("python3", "-c", "import platform; print('.'.join(platform.python_version_tuple()[:2]))").Output() + require.NoError(t, err) + return strings.TrimSpace(string(output)) +} + +// installFakePythonRunner makes the repository run its tests through the fake runner, with no runtime tags set. +func installFakePythonRunner(t *testing.T) string { + t.Helper() + version := hostPythonVersion(t) + installCommandCollector(t, "0") + viper.Reset() + settings.Init() + planTestFile(t, "scripts/run-tests", fakePythonRunner) + planTestFile(t, "scripts/uv-run-script", "#!/bin/sh\nexec python3 \"$@\"\n") + planTestFile(t, "env/bin/python", fakeEnvironmentPython) + planTestFile(t, "env/bin/pytest", fakeEnvironmentPytest) + planTestFile(t, "env/bin/python-entry", fakeEntryPointPython) + for _, file := range []string{"scripts/run-tests", "scripts/uv-run-script", "env/bin/python", "env/bin/pytest", "env/bin/python-entry"} { + require.NoError(t, os.Chmod(file, 0755)) + } + t.Setenv("FAKE_RUNNER_PYTHON", version) + return version +} + +func runnerCommand(id, job, suite string) CallerCommand { + return CallerCommand{ID: id, Job: job, Argv: []string{"scripts/run-tests", "--venv", "env-" + suite}, Cwd: ".", + Runner: &RunnerReference{Suite: suite, Environment: "env-" + suite}} +} + +func TestCollectCommandsInARunnerEnvironment(t *testing.T) { + newSkippableBackend(t) + clearIdentityVariables(t) + planRepositoryFixture(t) + planTestSettings(t) + version := installFakePythonRunner(t) + t.Setenv("DD_API_KEY", "real-key") + t.Setenv("DD_APP_KEY", "real-app-key") + command := runnerCommand("unit", "unit (env-unit)", "unit") + command.Env = map[string]string{"COMMAND_FLAG": "set-by-job"} + command.Runner.Args = []string{"-k", "actual test"} + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{command}, "inventories", &output)) + + inventory := readFixtureInventory(t, filepath.Join("inventories", "unit.json.gz")) + require.True(t, inventory.Complete, inventory.Errors) + require.Equal(t, command.Runner, inventory.Identity.Runner, "the identity names the runner environment") + require.Equal(t, command.Argv, inventory.Identity.Argv, "the identity keeps the job's command") + require.Len(t, inventory.Tests, 1) + require.Equal(t, "tests/test_actual.py", inventory.Tests[0].SuiteSourceFile) + require.Equal(t, "pytest.ini", inventory.Identity.PytestConfig.File) + + require.Equal(t, version, majorMinor(inventory.Inputs.Configurations["runtime.version"]), "the environment's interpreter runtime") + require.Equal(t, "env-unit", inventory.Inputs.Configurations["test.configuration.env_hash"], "the runner's custom tags") + require.Equal(t, map[string]string{"_CI_DD_TAGS": "test.configuration.env_hash:env-unit", "_DD_CIVISIBILITY_ITR_PREVENT_TEST_SKIPPING": "0"}, + inventory.Datadog.Variables, "the identity is the one the runner gives the command") + require.NotEmpty(t, inventory.Inputs.VenvSHA256) + + entryPointCalls := readLines(t, "entry-point-calls.txt") + require.Contains(t, entryPointCalls, "-c", "the interpreter the entry point names is probed") + require.True(t, strings.HasSuffix(entryPointCalls[0], "pytest"), "the probes run after the command, which may install dependencies as it starts: %v", entryPointCalls) + require.Equal(t, []string{"-c", "-c"}, entryPointCalls[1:]) + _, err := os.Stat("python-calls.txt") + require.True(t, os.IsNotExist(err), "the python on PATH is not the one pytest runs") + require.Equal(t, []string{"dummy_key"}, readLines(t, "api-keys.txt")[:1], "the runner never gets the Datadog key") + addopts := readLines(t, "addopts.txt")[0] + for _, option := range []string{"-p no:cacheprovider", "--ddtrace", "--collect-only"} { + require.Contains(t, addopts, option, "the worker adds the discovery options to the runner's PYTEST_ADDOPTS") + } + require.Equal(t, []string{"-k", "actual test", "tests/test_actual.py"}, readLines(t, "arguments.txt"), "the job's arguments reach the command") + require.Equal(t, []string{"set-by-job"}, readLines(t, "command-flag.txt"), "collection keeps the command's whole environment") + discoveryKey := readLines(t, "listings.txt") + require.Len(t, discoveryKey, 2, "one listing and one collection load the runner") + entries, err := os.ReadDir(".testoptimization") + require.NoError(t, err) + for _, entry := range entries { + require.False(t, strings.HasPrefix(entry.Name(), "runner-"), "the runner scripts are removed") + } +} + +func TestSelectCommandsInRunnerEnvironments(t *testing.T) { + newSkippableBackend(t) + clearIdentityVariables(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + multi := runnerCommand("multi", "multi", "multi") + index := 1 + multi.Runner.Invocation = &index + commands := []CallerCommand{runnerCommand("unit", "unit", "unit"), multi, runnerCommand("guarded", "guarded", "guarded")} + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).SelectCommands(t.Context(), Options{Output: "selection.json"}, commands, &output)) + var selection catalogSelection + require.NoError(t, json.Unmarshal(output.Bytes(), &selection)) + require.Equal(t, "skip", selection.Jobs[0].Decision, selection.Commands[0].Reason) + require.Equal(t, "skip", selection.Jobs[1].Decision, selection.Commands[1].Reason) + require.Equal(t, "run", selection.Jobs[2].Decision, "the runner's skipping control keeps the command running") + require.Len(t, readLines(t, "listings.txt"), 4, "the commands share one listing") +} + +func TestRunnerCommandsThatCannotBeCollected(t *testing.T) { + for name, test := range map[string]struct { + command CallerCommand + reason string + }{ + "several commands": {runnerCommand("multi", "multi", "multi"), "runs 2 commands; name one with runner.invocation"}, + "a shell program": {runnerCommand("shell", "shell", "shell"), "is a shell program"}, + "no framework": {runnerCommand("script", "script", "script"), "requires a pytest invocation"}, + "an unknown suite": {runnerCommand("missing", "missing", "missing"), `no suite "missing"`}, + "another Python": {runnerCommand("old", "old", "old"), "declares runtime 2.7, but its command collects with CPython"}, + "an unknown index": {func() CallerCommand { + c := runnerCommand("unit", "unit", "unit") + i := 3 + c.Runner.Invocation = &i + return c + }(), "no invocation 3"}, + "another directory": {func() CallerCommand { c := runnerCommand("unit", "unit", "unit"); c.Cwd = "sub"; return c }(), "repository root"}, + } { + t.Run(name, func(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + require.NoError(t, os.MkdirAll("sub", 0755)) + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{test.command}, "inventories", &output)) + inventory := readFixtureInventory(t, filepath.Join("inventories", test.command.ID+".json.gz")) + require.False(t, inventory.Complete) + require.Contains(t, strings.Join(inventory.Errors, "; "), test.reason) + }) + } +} + +func TestRunnerChecksTheMeasuredRuntimeBeforeRuntimeTags(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + // Runtime tags that name the declared Python don't hide that the environment collects with another one. + viper.Set("runtime_tags", strings.Replace(planRuntimeTags, "3.12.9", "2.7.18", 1)) + settings.Init() + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{runnerCommand("old", "old", "old")}, "inventories", &output)) + inventory := readFixtureInventory(t, filepath.Join("inventories", "old.json.gz")) + require.Contains(t, strings.Join(inventory.Errors, "; "), "declares runtime 2.7, but its command collects with CPython 3.") +} + +func TestRunnerRuntimeTagsMustNameTheMeasuredRuntime(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + version := installFakePythonRunner(t) + viper.Set("runtime_tags", strings.Replace(planRuntimeTags, "3.12.9", "2.7.18", 1)) + settings.Init() + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{runnerCommand("unit", "unit", "unit")}, "inventories", &output)) + inventory := readFixtureInventory(t, filepath.Join("inventories", "unit.json.gz")) + require.Contains(t, strings.Join(inventory.Errors, "; "), "--runtime-tags declare Python 2.7.18, but the command collects with Python "+version) +} + +func TestRunnerListingRequiresTheRunnerInterface(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + // A runner that only mentions a listing option is not one ddtest can list. + planTestFile(t, "scripts/run-tests", "import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('--list')\nparser.add_argument('--all-suites')\n") + _, err := newPythonRunner().resolve(t.Context(), RunnerReference{Suite: "unit", Environment: "env-unit"}) + require.ErrorContains(t, err, "unsupported runner interface: scripts/run-tests defines no TestRunner class") + + require.NoError(t, os.Remove("scripts/uv-run-script")) + _, err = newPythonRunner().resolve(t.Context(), RunnerReference{Suite: "unit", Environment: "env-unit"}) + require.ErrorContains(t, err, "scripts/uv-run-script, which is missing") +} + +func TestRunnerListingIsBounded(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + limit, delay := pythonRunnerListingLimit, pythonRunnerListingWaitDelay + t.Cleanup(func() { pythonRunnerListingLimit, pythonRunnerListingWaitDelay = limit, delay }) + + pythonRunnerListingLimit = 64 + planTestFile(t, "scripts/uv-run-script", "#!/bin/sh\nhead -c 100000 /dev/zero | tr '\\0' x\n") + _, err := newPythonRunner().resolve(t.Context(), RunnerReference{Suite: "unit", Environment: "env-unit"}) + require.ErrorContains(t, err, "runner listing exceeds 64 bytes") + + pythonRunnerListingWaitDelay = 100 * time.Millisecond + planTestFile(t, "scripts/uv-run-script", "#!/bin/sh\nsleep 30 &\necho $! > child.pid\necho '{\"suites\":[]}'\n") + started := time.Now() + _, err = newPythonRunner().resolve(t.Context(), RunnerReference{Suite: "unit", Environment: "env-unit"}) + require.Error(t, err, "a descendant holding the output open fails the listing") + require.Less(t, time.Since(started), 10*time.Second, "the listing does not wait for the descendant") + pid := readLines(t, "child.pid")[0] + // Where nothing reaps orphans, as in some containers, the killed descendant stays a zombie. + require.Eventually(t, func() bool { + status, err := exec.Command("ps", "-o", "stat=", "-p", pid).Output() + return err != nil || strings.HasPrefix(strings.TrimSpace(string(status)), "Z") + }, 5*time.Second, 50*time.Millisecond, "the descendant doesn't outlive the listing") +} + +func TestCappedOutputHasNoReadFrom(t *testing.T) { + output := &cappedOutput{limit: 4} + _, isReaderFrom := any(output).(io.ReaderFrom) + require.False(t, isReaderFrom, "io.Copy must write through the cap") + n, err := io.Copy(output, strings.NewReader("123456789")) + require.NoError(t, err) + require.EqualValues(t, 9, n) + require.Equal(t, "1234", output.String()) + require.True(t, output.truncated) +} + +func TestInlineScriptMetadata(t *testing.T) { + require.Equal(t, "# /// script\n# dependencies = [\n# \"packaging\",\n# ]\n# ///\n", + inlineScriptMetadata([]byte("#!/usr/bin/env scripts/uv-run-script\n# -*- mode: python -*-\n# /// script\n# dependencies = [\n# \"packaging\",\n# ]\n# ///\n\"\"\"Doc.\"\"\"\n"))) + require.Empty(t, inlineScriptMetadata([]byte("import os\n"))) + require.Empty(t, inlineScriptMetadata([]byte("# /// script\nimport os\n")), "an unterminated block is no metadata") +} + +func TestCommandWords(t *testing.T) { + for command, want := range map[string][]string{ + "pytest -v --ignore-glob='*civisibility*' tests/integration/": {"pytest", "-v", "--ignore-glob=*civisibility*", "tests/integration/"}, + "pytest -m 'not (slow or integration)' tests": {"pytest", "-m", "not (slow or integration)", "tests"}, + `pytest -k "a and not b" tests\ dir`: {"pytest", "-k", "a and not b", "tests dir"}, + } { + words, ok := commandWords(command) + require.True(t, ok, command) + require.Equal(t, want, words) + } + for _, command := range []string{"pytest a && pytest b", "pytest a; pytest b", "pytest $TESTS", `pytest "$TESTS"`, "pytest tests/*.py", + "pytest > out", "pytest `ls`", "", "pytest 'unterminated"} { + _, ok := commandWords(command) + require.False(t, ok, command) + } +} + +func TestReadCommandsChecksTheRunner(t *testing.T) { + t.Chdir(t.TempDir()) + commands, err := ReadCommands(writeCommandsFile(t, "commands.json", map[string]any{"schema_version": 1, "commands": []any{ + map[string]any{"id": "unit", "job": "unit", "argv": []string{"scripts/run-tests", "--venv", "abc"}, + "runner": map[string]any{"suite": "tracer", "environment": "abc", "invocation": 1, "args": []string{"-k", "x"}}}, + }})) + require.NoError(t, err) + index := 1 + require.Equal(t, &RunnerReference{Suite: "tracer", Environment: "abc", Invocation: &index, Args: []string{"-k", "x"}}, commands[0].Runner) + for name, runner := range map[string]map[string]any{ + "no suite": {"environment": "abc"}, + "no environment": {"suite": "tracer"}, + "a negative invocation": {"suite": "tracer", "environment": "abc", "invocation": -1}, + } { + t.Run(name, func(t *testing.T) { + _, err := ReadCommands(writeCommandsFile(t, "commands.json", map[string]any{"schema_version": 1, "commands": []any{ + map[string]any{"id": "unit", "job": "unit", "argv": []string{"scripts/run-tests"}, "runner": runner}, + }})) + require.ErrorContains(t, err, "runner") + }) + } +} + +func readLines(t *testing.T, path string) []string { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + return strings.Split(strings.TrimRight(string(data), "\n"), "\n") +} + +func TestRunnerCommandsUseTheServiceTheRunnerSets(t *testing.T) { + newSkippableBackend(t) + clearIdentityVariables(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).SelectCommands(t.Context(), Options{Output: "selection.json"}, []CallerCommand{runnerCommand("service", "service", "service")}, &output)) + var selection catalogSelection + require.NoError(t, json.Unmarshal(output.Bytes(), &selection)) + require.Equal(t, "runner-service", selection.Commands[0].Service) + require.Equal(t, "skip", selection.Jobs[0].Decision, selection.Commands[0].Reason) +} + +func TestRunnerInventoriesDecideOnlyForTheirCommit(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installFakePythonRunner(t) + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{runnerCommand("unit", "unit", "unit")}, "inventories", &output)) + path, err := filepath.Abs(filepath.Join("inventories", "unit.json.gz")) + require.NoError(t, err) + earlier := readFixtureInventory(t, path).Identity.Commit + leaveCheckout(t) + + t.Setenv("DD_GIT_COMMIT_SHA", earlier) + require.Equal(t, "skip", selectWithChangedFiles(t, nil, path).Jobs[0].Decision, "the inventory decides for its own commit") + t.Setenv("DD_GIT_COMMIT_SHA", strings.Repeat("3", 40)) + selection := selectWithChangedFiles(t, []string{}, path) + require.Equal(t, "run", selection.Jobs[0].Decision, "even with no changes listed") + require.Contains(t, selection.Commands[0].Reason, "a repository runner's definitions can change what its command collects") +} diff --git a/internal/selection/runner.go b/internal/selection/runner.go new file mode 100644 index 000000000..50520511b --- /dev/null +++ b/internal/selection/runner.go @@ -0,0 +1,135 @@ +package selection + +import ( + "bytes" + "context" + "fmt" + "strings" + + "github.com/kballard/go-shellquote" + + "github.com/DataDog/ddtest/internal/platform" + "github.com/DataDog/ddtest/internal/testoptimization" +) + +// commandRunner collects commands that run their tests through a repository's own runner: the runner lists the +// test environments it prepares and the command each runs, and prepares the environment itself when collection runs +// ddtest's worker there in place of the command. A runner for another platform joins by implementing it and +// adding itself to commandRunners. +type commandRunner interface { + // resolve returns the invocation reference names, from the runner's listing. + resolve(ctx context.Context, reference RunnerReference) (runnerInvocation, error) + // collect collects the invocation inside its environment, and reports the values the command's environment + // gives the named variables. + collect(ctx context.Context, invocation runnerInvocation, framework, pluginGroup string, variables []string) (runnerCollection, error) +} + +// commandRunners are the repository runners collection supports, by platform. +var commandRunners = map[string]func() commandRunner{ + "python": func() commandRunner { return newPythonRunner() }, +} + +// runnerInvocation is a test command of a runner environment. +type runnerInvocation struct { + Reference RunnerReference + // Command is the command line the runner runs, with the job's arguments in place. + Command string + // Argv is Command's words. + Argv []string + // RuntimeVersion is the runtime version the runner declares for the environment. + RuntimeVersion string +} + +// runnerCollection is what the worker found inside the runner's environment. +type runnerCollection struct { + Tests []testoptimization.Test + // RuntimeTags are the runtime tags of the interpreter the command runs, as the worker measured them. + RuntimeTags map[string]string + Packages platform.CommandPackages + // Variables are the requested variables of the command's environment, as the runner set them. + Variables map[string]string +} + +// runner returns the repository runner of the selector's platform. The selector keeps it, so a runner can list its +// environments once for the commands that share an environment. +func (s *Selector) runner() (commandRunner, error) { + if s.commandRunner != nil { + return s.commandRunner, nil + } + newRunner, ok := commandRunners[s.platform.Name()] + if !ok { + return nil, fmt.Errorf("collection supports no repository runner for platform %q", s.platform.Name()) + } + s.commandRunner = newRunner() + return s.commandRunner, nil +} + +// runnerVersionMatches reports whether a measured runtime version is the version a runner declares, such as 3.12 +// for 3.12.9. +func runnerVersionMatches(measured, declared string) bool { + return measured != "" && (measured == declared || strings.HasPrefix(measured, declared+".")) +} + +// shellSyntax are the characters that, unquoted, make a runner's command line more than one command, or let the shell +// change the words it runs. Inside double quotes, the shell still expands $ and `. +const ( + shellSyntax = ";&|<>`$(){}*?[]~!#\n" + doubleQuoteSyntax = "$`" +) + +// commandWords splits a runner's command line into the words of the one command it runs. ok is false when the line +// is a shell program instead, which collection can't take as one command. Quoted characters are literal. +func commandWords(command string) ([]string, bool) { + var quote rune + escaped := false + for _, c := range command { + switch { + case escaped: + escaped = false + case quote == '\'': + if c == '\'' { + quote = 0 + } + case quote == '"': + if c == '"' { + quote = 0 + } else if c == '\\' { + escaped = true + } else if strings.ContainsRune(doubleQuoteSyntax, c) { + return nil, false + } + case c == '\\': + escaped = true + case c == '\'' || c == '"': + quote = c + case strings.ContainsRune(shellSyntax, c): + return nil, false + } + } + words, err := shellquote.Split(command) + if err != nil || len(words) == 0 { + return nil, false + } + return words, true +} + +// cappedOutput keeps the first limit bytes written to it. It has no ReadFrom, so a command's output reaches it only +// through Write. +type cappedOutput struct { + buffer bytes.Buffer + limit int + truncated bool +} + +func (o *cappedOutput) Write(data []byte) (int, error) { + n := len(data) + if remaining := o.limit - o.buffer.Len(); len(data) > remaining { + data = data[:remaining] + o.truncated = true + } + _, _ = o.buffer.Write(data) + return n, nil +} + +func (o *cappedOutput) Bytes() []byte { return o.buffer.Bytes() } +func (o *cappedOutput) String() string { return o.buffer.String() } diff --git a/internal/selection/scripts/python_runner.py b/internal/selection/scripts/python_runner.py new file mode 100644 index 000000000..a4b289c54 --- /dev/null +++ b/internal/selection/scripts/python_runner.py @@ -0,0 +1,47 @@ +"""Load the repository's test runner, scripts/run-tests, and check that it has the interface ddtest uses.""" + +import dataclasses +import runpy +import sys + +UNSUPPORTED = 3 + + +def unsupported(reason): + sys.stderr.write("unsupported runner interface: " + reason + "\n") + raise SystemExit(UNSUPPORTED) + + +def load_runner(): + namespace = runpy.run_path("scripts/run-tests") + runner_class = namespace.get("TestRunner") + if not isinstance(runner_class, type): + unsupported("scripts/run-tests defines no TestRunner class") + runner = runner_class() + if not isinstance(getattr(runner, "environments", None), dict): + unsupported("TestRunner has no environments by suite") + if not callable(getattr(runner, "run_tests", None)): + unsupported("TestRunner has no run_tests") + return runner + + +def check_environment(environment): + for name in ("hash", "python", "runs"): + if not hasattr(environment, name): + unsupported("a test environment has no " + name) + if not dataclasses.is_dataclass(environment) or not isinstance(environment.hash, str): + unsupported("a test environment is not a dataclass with a hash") + for run in environment.runs: + if not dataclasses.is_dataclass(run) or "env" not in {field.name for field in dataclasses.fields(run)}: + unsupported("a test run is not a dataclass with an env") + if not isinstance(run.command, str) or not isinstance(run.environment, dict): + unsupported("a test run has no command and environment") + + +def find_environment(runner, suite, environment_hash): + for environment in runner.environments.get(suite, ()): + check_environment(environment) + if environment.hash == environment_hash: + return environment + sys.stderr.write("suite %r has no test environment %r\n" % (suite, environment_hash)) + raise SystemExit(1) diff --git a/internal/selection/scripts/python_runner_catalog.py b/internal/selection/scripts/python_runner_catalog.py new file mode 100644 index 000000000..a537ab2d7 --- /dev/null +++ b/internal/selection/scripts/python_runner_catalog.py @@ -0,0 +1,21 @@ +"""List the repository runner's suites, their test environments and the commands each runs, without preparing them.""" + +import json +import sys + +from ddtest_python_runner import check_environment +from ddtest_python_runner import load_runner + +# The runner may print as it loads; only the listing goes to stdout. +stdout, sys.stdout = sys.stdout, sys.stderr +runner = load_runner() +suites = [] +for name, environments in runner.environments.items(): + listed = [] + for environment in environments: + check_environment(environment) + listed.append({"hash": environment.hash, "python": str(environment.python), + "invocations": [{"command": run.command} for run in environment.runs]}) + suites.append({"name": name, "environments": listed}) +json.dump({"suites": suites}, stdout) +stdout.flush() diff --git a/internal/selection/scripts/python_runner_collection.py b/internal/selection/scripts/python_runner_collection.py new file mode 100644 index 000000000..8fa5dfc68 --- /dev/null +++ b/internal/selection/scripts/python_runner_collection.py @@ -0,0 +1,25 @@ +"""Run one test invocation of the repository runner with ddtest's worker in place of its command. + +The runner prepares the invocation's environment and runs the worker there, with the variables it would give the +command. The discovery variables of this process join them, so the worker collects into ddtest's report. +""" + +from dataclasses import replace +import json +import os +import sys + +from ddtest_python_runner import find_environment +from ddtest_python_runner import load_runner + +with open(sys.argv[1]) as stream: + selection = json.load(stream) + +runner = load_runner() +environment = find_environment(runner, selection["suite"], selection["environment"]) +run = environment.runs[selection["invocation"]] +variables = dict(run.environment) +variables.update({key: os.environ[key] for key in selection["discovery_variables"] if key in os.environ}) +worker = replace(run, command=selection["worker_command"], env=tuple(variables.items())) +if not runner.run_tests([replace(environment, runs=(worker,))], test_args=[]): + raise SystemExit(1) diff --git a/internal/selection/scripts/python_runner_worker.py b/internal/selection/scripts/python_runner_worker.py new file mode 100644 index 000000000..5b132e5d8 --- /dev/null +++ b/internal/selection/scripts/python_runner_worker.py @@ -0,0 +1,63 @@ +"""Collect a runner's test command inside the environment the runner prepared for it. + +The runner runs this worker in place of the command. It records the variables the command would see, runs the +command for collection only, and then probes the Python the command ran. +""" + +import json +import os +import shutil +import subprocess +import sys + +with open(sys.argv[1]) as stream: + selection = json.load(stream) + +# The second line of the /bin/sh wrapper that uv writes for a relocatable environment's entry point. +RELOCATABLE = "'''exec' \"$(dirname -- \"$(realpath -- \"$0\")\")\"/" +# The second line of the /bin/sh wrapper that pip writes when the interpreter's path doesn't fit on the #! line. +WRAPPED = "'''exec' \"" + + +def entry_point_interpreter(entry_point): + """The Python a pytest entry point runs, as the interpreter line of its script names it.""" + path = shutil.which(entry_point) + if path is None: + sys.exit("cannot find the pytest entry point %s in the runner's environment" % entry_point) + target = os.path.realpath(path) + with open(target, "rb") as stream: + lines = stream.read(4096).decode("utf-8", "replace").split("\n", 3) + fields = lines[0].strip()[2:].split() if lines[0].startswith("#!") else [] + interpreter = None + if fields and os.path.basename(fields[0]) == "env": + interpreter = next((field for field in fields[1:] if not field.startswith("-")), None) + elif fields and os.path.basename(fields[0]) == "sh" and len(lines) > 1: + wrapper = lines[1].strip() + if wrapper.startswith(RELOCATABLE): + name = wrapper[len(RELOCATABLE):].split(" ", 1)[0].strip("'\"") + interpreter = os.path.join(os.path.dirname(target), name) + elif wrapper.startswith(WRAPPED): + interpreter = wrapper[len(WRAPPED):].split('"', 1)[0] + elif fields: + interpreter = fields[0] + if not interpreter or not os.path.basename(interpreter).startswith("python"): + sys.exit("cannot identify the Python that the pytest entry point %s runs" % entry_point) + return interpreter + + +probe = selection["probe"] or [entry_point_interpreter(selection["entry_point"])] +# The command's variables as the runner set them, before this worker adds its own. +variables = {key: os.environ[key] for key in selection["variables"] if key in os.environ} +with open(selection["variables_file"], "w") as stream: + json.dump(variables, stream) +# The runner's variables may replace PYTEST_ADDOPTS, so the discovery options are added again. +os.environ["PYTEST_ADDOPTS"] = (os.environ.get("PYTEST_ADDOPTS", "") + " " + selection["addopts"]).strip() +sys.stdout.flush() +status = subprocess.call(["bash", "-c", selection["command"]]) +if status != 0: + sys.exit(status) +# The command may install dependencies as it starts, as uv run does, so the interpreter is probed after it ran. +subprocess.check_call(probe + ["-c", selection["runtime_script"], selection["runtime_file"]]) +subprocess.check_call( + probe + ["-c", selection["packages_script"], selection["packages_file"], selection["plugin_group"], selection["framework"]] +) diff --git a/internal/selection/selection.go b/internal/selection/selection.go index 249c76018..382c4ab18 100644 --- a/internal/selection/selection.go +++ b/internal/selection/selection.go @@ -67,6 +67,8 @@ type Selector struct { platform platform.Platform framework framework.Framework telemetryClient telemetry.Client + // commandRunner is the platform's repository runner, once a command runs in it. + commandRunner commandRunner } // New returns a Selector for the selected platform and framework.