From 8dc322da75802491c98e6e9f3474457aaff51e11 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Fri, 4 Dec 2026 15:16:20 +0100 Subject: [PATCH 1/7] Take test commands from the caller in select and collect select --commands and collect --commands read a commands file that lists each CI job's commands, with their argv, cwd and environment. Each command is collected with its job's env applied, so collection, its probes, the identity Datadog is asked about and the inventory see the command's values. collect writes one inventory per command to --output-dir; select decides every command and rolls them up per job. Co-Authored-By: Claude Opus 5.5 --- docs/running.md | 49 +++++++ internal/cmd/cmd.go | 4 +- internal/cmd/select.go | 59 +++++++- internal/cmd/select_test.go | 37 ++++- internal/selection/collect.go | 41 ++++-- internal/selection/commands.go | 144 +++++++++++++++++++ internal/selection/commands_test.go | 210 ++++++++++++++++++++++++++++ internal/selection/decide.go | 25 +++- internal/selection/inventory.go | 3 + internal/selection/selection.go | 56 ++++++++ 10 files changed, 609 insertions(+), 19 deletions(-) create mode 100644 internal/selection/commands.go create mode 100644 internal/selection/commands_test.go diff --git a/docs/running.md b/docs/running.md index 030f782a..cd3be369 100644 --- a/docs/running.md +++ b/docs/running.md @@ -977,6 +977,55 @@ The selected jobs can avoid test execution, but selection does not promise to av Existing saved worker plans and response caches remain unchanged. `ddtest plan` keeps its existing behavior. +### Commands from the caller + +By default `select` and `collect` take one test command, from `--command` or the framework's default. A pipeline +generator or an orchestrator already knows every CI job's commands and the environment each runs in. It can list +them in a commands file instead: + +```json +{ + "schema_version": 1, + "commands": [ + {"id": "unit-py312", "job": "test (ubuntu-latest, 3.12)", "env_hash": "py312", + "argv": [".venv/bin/python", "-m", "pytest", "tests/unit"], "cwd": ".", + "env": {"DD_ENV": "ci", "PYTHONHASHSEED": "0"}}, + {"id": "integration-py312", "job": "integration (3.12)", + "argv": [".venv/bin/python", "-m", "pytest", "tests/integration"]} + ] +} +``` + +```sh +# collect and decide in one place +ddtest select --commands commands.json --output selection.json + +# or collect each command into its own inventory, and decide elsewhere +ddtest collect --commands commands.json --output-dir inventories +ddtest select --inventory inventories/unit-py312.json.gz --inventory inventories/integration-py312.json.gz --output selection.json +``` + +A command uses the field names of an inventory's identity, so a commands file is the inventories before collection: + +- `id` names the command in the selection, and its inventory file, `.json.gz`. It is letters, digits, `.`, `_` + and `-`, and is unique in the file. +- `job` is the CI job the command belongs to. Commands with the same `job` are that job's commands, and the job + skips only when all of them can. +- `env_hash` is the job's environment hash, as `collect --env-hash` takes it. Optional. +- `argv` is the command, unchanged; `cwd` is where it runs, `.` by default. Collection supports commands that run at + the repository root; any other `cwd` keeps the command at `run`. +- `env` holds the variables the job sets for the command, on top of ddtest's own environment. Collection, its + runtime and package probes, the identity Datadog is asked about and the inventory's environment hashes all see + them, as the job would run the command. Runtime tags a command's `env` declares, such as + `DD_TEST_OPTIMIZATION_RUNNER_RUNTIME_TAGS`, are checked against the interpreter that collects, as `--runtime-tags` + are; `--runtime-tags` wins over them. `env` may not set `DD_API_KEY`, `DD_APP_KEY` or `DD_GIT_*`: collection never + passes Datadog keys to repository code, and git values come from the checkout. + +With `--commands`, `select` and `collect` take no `--command` or test patterns, and `collect` takes `--output-dir` +instead of `--output`, `--job` and `--env-hash`. `collect --commands` prints a JSON list of the inventories it wrote, +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. + ### Collect in one place, select in another Collection needs the test environment; the decision needs Datadog credentials. diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go index 92e1cd7e..5fca4951 100644 --- a/internal/cmd/cmd.go +++ b/internal/cmd/cmd.go @@ -84,7 +84,7 @@ var planCmd = &cobra.Command{ var selectCmd = &cobra.Command{ Use: "select", Short: "Decide which CI test commands can skip", - Long: "Collects the project's test command as CI runs it and decides, with suite-level Test Impact Analysis, whether the command can skip. Writes the decisions as JSON to --output. Collection imports project modules but does not run test bodies. With --inventory, decides from inventories that ddtest collect wrote instead, without a checkout. Supports Python with pytest.", + Long: "Collects the project's test command as CI runs it and decides, with suite-level Test Impact Analysis, whether the command can skip. Writes the decisions as JSON to --output. Collection imports project modules but does not run test bodies. With --commands, collects and decides every command that a commands file lists for each CI job, each with its job's environment; a job skips only when all its commands can. With --inventory, decides from inventories that ddtest collect wrote instead, without a checkout. Supports Python with pytest.", Args: validateSelectArguments, Run: runSelectCommand, } @@ -92,7 +92,7 @@ var selectCmd = &cobra.Command{ var collectCmd = &cobra.Command{ Use: "collect", Short: "Collect the project's test command into an inventory", - Long: "Collects the project's test command as CI runs it, with every test it runs, the identity its workers report and fingerprints of its environment, and writes them as a gzipped inventory JSON file to --output. Prints the inventory's environment and exact keys, which find it again for the same command and environment on any commit or on this one. ddtest select --inventory decides from the file where the checkout is not available. Collection imports project modules but does not run test bodies. With DD_API_KEY set, it uploads the checkout's git metadata to Datadog, which select --inventory needs, and keeps the key from the commands it runs; otherwise it sends nothing to Datadog. Supports Python with pytest.", + Long: "Collects the project's test command as CI runs it, with every test it runs, the identity its workers report and fingerprints of its environment, and writes them as a gzipped inventory JSON file to --output. Prints the inventory's environment and exact keys, which find it again for the same command and environment on any commit or on this one. With --commands, collects every command that a commands file lists for each CI job, each with its job's environment, and writes one inventory per command to --output-dir. ddtest select --inventory decides from the file where the checkout is not available. Collection imports project modules but does not run test bodies. With DD_API_KEY set, it uploads the checkout's git metadata to Datadog, which select --inventory needs, and keeps the key from the commands it runs; otherwise it sends nothing to Datadog. Supports Python with pytest.", Args: validateCollectArguments, Run: runCollectCommand, } diff --git a/internal/cmd/select.go b/internal/cmd/select.go index ff29d010..0ea5b140 100644 --- a/internal/cmd/select.go +++ b/internal/cmd/select.go @@ -21,12 +21,15 @@ var collectionRootFlags = []string{"platform", "framework", "command", "test-ski func addSelectFlags(cmd *cobra.Command) { cmd.Flags().String("output", "", "Write CI command decisions as JSON") cmd.Flags().StringArray("inventory", nil, "Decide from an inventory that ddtest collect wrote, instead of collecting (repeat for inventories collected in different places)") + cmd.Flags().String("commands", "", "Collect and decide the commands that a JSON commands file lists for each CI job, instead of the project's test command") cmd.Flags().String("changed-files", "", "With --inventory: a file listing the paths changed between the inventories' commits and the selected commit, one per line, such as git diff --name-only --no-renames writes (-z output works too); a change that can affect collection keeps an earlier commit's inventory from skipping") showOnlyCollectionRootFlags(cmd) } func addCollectFlags(cmd *cobra.Command) { cmd.Flags().String("output", "", "Write the collected test commands as an inventory JSON file") + cmd.Flags().String("commands", "", "Collect the commands that a JSON commands file lists for each CI job, instead of the project's test command; requires --output-dir") + cmd.Flags().String("output-dir", "", "With --commands: write one inventory per command to this directory, as .json.gz") cmd.Flags().String("job", "", "Name of the collected CI job and its command in the inventory and the selection (default: the framework name); give each collection that select reads together its own name") cmd.Flags().String("env-hash", "", "Environment hash of the CI job, such as a test matrix runner computes, recorded in the inventory's identity") cmd.Flags().StringArray("lock-file", nil, "Lock file the job installs from (repeatable; default: the platform's lock files at the repository root)") @@ -78,10 +81,37 @@ func selectInventories(cmd *cobra.Command) []string { return inventories } +// validateCommandsArguments rejects the collection flags a commands file replaces: the command, its test selection, +// and, for collect, the job and environment hash, which each listed command carries. +func validateCommandsArguments(cmd *cobra.Command, args []string, replaced ...string) error { + if len(args) != 0 || settings.GetTestsLocation() != "" { + return fmt.Errorf("%s --commands takes each command's tests from its argv, so drop the test patterns", cmd.Name()) + } + var conflicting []string + for _, name := range append([]string{"command"}, replaced...) { + if flag := cmd.Flags().Lookup(name); flag != nil && flag.Changed { + conflicting = append(conflicting, "--"+name) + } + } + if len(conflicting) > 0 { + return fmt.Errorf("%s --commands takes every command from the file, so drop %s", cmd.Name(), strings.Join(conflicting, ", ")) + } + return validateCollectionArguments(cmd, args) +} + func validateSelectArguments(cmd *cobra.Command, args []string) error { if selectFlag(cmd, "output") == "" { return fmt.Errorf("select requires --output") } + if selectFlag(cmd, "commands") != "" { + if len(selectInventories(cmd)) > 0 { + return fmt.Errorf("select takes --commands or --inventory, not both") + } + if cmd.Flags().Changed("changed-files") { + return fmt.Errorf("select --changed-files requires --inventory") + } + return validateCommandsArguments(cmd, args) + } if len(selectInventories(cmd)) == 0 && cmd.Flags().Changed("changed-files") { return fmt.Errorf("select --changed-files requires --inventory") } @@ -101,6 +131,15 @@ func validateSelectArguments(cmd *cobra.Command, args []string) error { } func validateCollectArguments(cmd *cobra.Command, args []string) error { + if selectFlag(cmd, "commands") != "" { + if selectFlag(cmd, "output-dir") == "" { + return fmt.Errorf("collect --commands requires --output-dir") + } + return validateCommandsArguments(cmd, args, "output", "job", "env-hash") + } + if cmd.Flags().Changed("output-dir") { + return fmt.Errorf("collect --output-dir requires --commands") + } if selectFlag(cmd, "output") == "" { return fmt.Errorf("collect requires --output") } @@ -146,7 +185,15 @@ func runSelection(cmd *cobra.Command, telemetryClient telemetry.Client) error { if err != nil { return err } - return selection.New(p, fw, telemetryClient).Select(commandContext(cmd), collectionOptions(cmd), cmd.OutOrStdout()) + selector := selection.New(p, fw, telemetryClient) + if file := selectFlag(cmd, "commands"); file != "" { + commands, err := selection.ReadCommands(file) + if err != nil { + return err + } + return selector.SelectCommands(commandContext(cmd), collectionOptions(cmd), commands, cmd.OutOrStdout()) + } + return selector.Select(commandContext(cmd), collectionOptions(cmd), cmd.OutOrStdout()) } // runCollection writes the project's inventory. Collection sends Datadog only the checkout's git metadata, and only @@ -166,5 +213,13 @@ func runCollection(cmd *cobra.Command) error { if options.LockFiles, err = cmd.Flags().GetStringArray("lock-file"); err != nil { return err } - return selection.New(p, fw, telemetry.NoopClient()).Collect(commandContext(cmd), options, cmd.OutOrStdout()) + selector := selection.New(p, fw, telemetry.NoopClient()) + if file := selectFlag(cmd, "commands"); file != "" { + commands, err := selection.ReadCommands(file) + if err != nil { + return err + } + return selector.CollectCommands(commandContext(cmd), options, commands, selectFlag(cmd, "output-dir"), cmd.OutOrStdout()) + } + return selector.Collect(commandContext(cmd), options, cmd.OutOrStdout()) } diff --git a/internal/cmd/select_test.go b/internal/cmd/select_test.go index d322e63c..cdd26ef3 100644 --- a/internal/cmd/select_test.go +++ b/internal/cmd/select_test.go @@ -22,7 +22,7 @@ func selectTestCommand() *cobra.Command { } func TestSelectRejectsDescriptionInputs(t *testing.T) { - for _, args := range [][]string{{"--commands", "commands.json", "--output", "selection.json"}, {"--output", "selection.json", "tests"}} { + for _, args := range [][]string{{"--output", "selection.json", "tests"}} { cmd := selectTestCommand() cmd.SetArgs(args) require.Error(t, cmd.Execute()) @@ -147,3 +147,38 @@ func TestCollectRequiresOutputAndRejectsNodeSplittingFlags(t *testing.T) { require.NotNil(t, collectCmd.Flags().Lookup("output")) require.Nil(t, collectCmd.Flags().Lookup("inventory")) } + +func TestCommandsFileArguments(t *testing.T) { + newRoot := func(sub *cobra.Command) *cobra.Command { + root := &cobra.Command{Use: "ddtest"} + root.PersistentFlags().String("command", "", "") + root.PersistentFlags().String("runtime-tags", "", "") + root.AddCommand(sub) + return root + } + for _, tc := range []struct { + command func() *cobra.Command + args []string + message string + }{ + {selectTestCommand, []string{"select", "--commands", "c.json", "--inventory", "i.json", "--output", "s.json"}, "not both"}, + {selectTestCommand, []string{"select", "--commands", "c.json", "--command", "pytest", "--output", "s.json"}, "drop --command"}, + {selectTestCommand, []string{"select", "--commands", "c.json", "--output", "s.json", "tests"}, "test patterns"}, + {selectTestCommand, []string{"select", "--commands", "c.json", "--changed-files", "x.txt", "--output", "s.json"}, "requires --inventory"}, + {collectTestCommand, []string{"collect", "--commands", "c.json"}, "requires --output-dir"}, + {collectTestCommand, []string{"collect", "--output-dir", "out"}, "requires --commands"}, + {collectTestCommand, []string{"collect", "--commands", "c.json", "--output-dir", "out", "--job", "unit"}, "drop --job"}, + {collectTestCommand, []string{"collect", "--commands", "c.json", "--output-dir", "out", "--output", "x.json.gz"}, "drop --output"}, + } { + root := newRoot(tc.command()) + root.SetArgs(tc.args) + root.SilenceUsage, root.SilenceErrors = true, true + require.ErrorContains(t, root.Execute(), tc.message, tc.args) + } + root := newRoot(selectTestCommand()) + root.SetArgs([]string{"select", "--commands", "missing.json", "--runtime-tags", "{}", "--output", "s.json"}) + root.SilenceUsage, root.SilenceErrors = true, true + err := root.Execute() + require.Error(t, err) + require.NotContains(t, err.Error(), "drop", "--runtime-tags still applies to every listed command") +} diff --git a/internal/selection/collect.go b/internal/selection/collect.go index 78681d87..8eaa0dd4 100644 --- a/internal/selection/collect.go +++ b/internal/selection/collect.go @@ -57,9 +57,32 @@ var startupEnviron = os.Environ() // collectionEnviron returns the collection environment the inventory records. var collectionEnviron = func() []string { return startupEnviron } -// collectProjectCommand collects the project's test command into an inventory. environ is the collection -// environment as ddtest received it. +// collectProjectCommand collects the project's test command, from --command or the framework's default, into an +// inventory. environ is the collection environment as ddtest received it. func (s *Selector) collectProjectCommand(ctx context.Context, options Options, environ []string) (Inventory, error) { + executable, args := s.framework.Command() + job := options.Job + if job == "" { + job = s.framework.Name() + } + command := CallerCommand{Job: job, EnvHash: options.EnvHash, Argv: append([]string{executable}, args...), Cwd: "."} + return s.collectCommand(ctx, options, command, environ) +} + +// collectCallerCommand collects one command of a commands file, with its env applied as its job sets it. +func (s *Selector) collectCallerCommand(ctx context.Context, options Options, command CallerCommand, environ []string) (Inventory, error) { + var inventory Inventory + err := withCommandEnvironment(command.Env, func() error { + var err error + inventory, err = s.collectCommand(ctx, options, command, overlayEnviron(environ, command.Env)) + return err + }) + return inventory, err +} + +// collectCommand collects command into an inventory. environ is the command's environment as its job runs it, +// before collection changes anything; the process environment holds the same values while it runs. +func (s *Selector) collectCommand(ctx context.Context, options Options, command CallerCommand, environ []string) (Inventory, error) { mode := options.TestSkippingLevel commandPlatform, ok := s.platform.(CommandPlatform) if !ok { @@ -79,12 +102,7 @@ func (s *Selector) collectProjectCommand(ctx context.Context, options Options, e if err != nil { return Inventory{}, err } - executable, args := fw.Command() - argv := append([]string{executable}, args...) - job := options.Job - if job == "" { - job = fw.Name() - } + argv, job := command.Argv, command.Job identity := collectionIdentity() lockFiles, lockSHA256, err := lockFileDigest(options.LockFiles, commandPlatform.CommandLockFiles()) if err != nil { @@ -98,7 +116,8 @@ func (s *Selector) collectProjectCommand(ctx context.Context, options Options, e inventory := Inventory{ SchemaVersion: InventorySchemaVersion, Identity: InventoryIdentity{Repo: repositoryName(checkout.RepositoryURL), Commit: checkout.Tags[constants.GitCommitSHA], - Job: job, EnvHash: options.EnvHash, Argv: argv, Cwd: "."}, + Job: job, EnvHash: command.EnvHash, Argv: argv, Cwd: filepath.ToSlash(filepath.Clean(command.Cwd))}, + CommandID: command.ID, Inputs: InventoryInputs{LockFiles: lockFiles, LockSHA256: lockSHA256, Image: image, Configurations: map[string]string{}, Plugins: map[string]string{}, Env: env, EnvExcluded: excluded, EnvSetByProducer: setByProducer}, Producer: InventoryProducer{Name: "ddtest", Version: buildinfo.CurrentVersion(), CreatedAt: time.Now().UTC().Format(time.RFC3339)}, @@ -108,7 +127,9 @@ func (s *Selector) collectProjectCommand(ctx context.Context, options Options, e Errors: []string{}, } frameworkArgs, runsFramework := commandPlatform.FrameworkArguments(fw.Name(), argv) - if !runsFramework { + 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") } else if reason := suitePlanningPolicy(identity); reason != "" { inventory.Errors = append(inventory.Errors, reason) diff --git a/internal/selection/commands.go b/internal/selection/commands.go new file mode 100644 index 00000000..8dbb2251 --- /dev/null +++ b/internal/selection/commands.go @@ -0,0 +1,144 @@ +package selection + +import ( + "encoding/json" + "fmt" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + + "github.com/DataDog/ddtest/internal/settings" +) + +// CommandsSchemaVersion is the commands file format this ddtest reads. +const CommandsSchemaVersion = 1 + +// CommandsFile lists the test commands a caller, such as a pipeline generator or an orchestrator, runs in its CI +// jobs. A command uses the field names of an inventory's identity: it is the inventory before collection. +type CommandsFile struct { + SchemaVersion int `json:"schema_version"` + Commands []CallerCommand `json:"commands"` +} + +// 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. +type CallerCommand struct { + ID string `json:"id"` + Job string `json:"job"` + EnvHash string `json:"env_hash"` + Argv []string `json:"argv"` + Cwd string `json:"cwd"` + Env map[string]string `json:"env"` +} + +// commandIDPattern keeps a command ID usable as a file name. +var commandIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +var variableNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// commandEnvironmentForbidden are variables a command's env may not set: Datadog keys, which collection never +// passes to repository code, and git values, which come from the checkout. +func commandEnvironmentForbidden(name string) bool { + return name == "DD_API_KEY" || name == "DD_APP_KEY" || strings.HasPrefix(name, "DD_GIT_") +} + +// ReadCommands reads and checks a commands file. +func ReadCommands(path string) ([]CallerCommand, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read commands: %w", err) + } + var file CommandsFile + if err := json.Unmarshal(data, &file); err != nil { + return nil, fmt.Errorf("decode commands %s: %w", path, err) + } + if file.SchemaVersion != CommandsSchemaVersion { + return nil, fmt.Errorf("commands %s: unsupported schema_version %d; this ddtest reads %d", path, file.SchemaVersion, CommandsSchemaVersion) + } + if len(file.Commands) == 0 { + return nil, fmt.Errorf("commands %s lists no commands", path) + } + seen := map[string]bool{} + for i, command := range file.Commands { + where := fmt.Sprintf("commands %s: command %d", path, i+1) + if !commandIDPattern.MatchString(command.ID) { + return nil, fmt.Errorf("%s: id %q must be letters, digits, '.', '_' or '-', starting with a letter or digit", where, command.ID) + } + where = fmt.Sprintf("commands %s: command %q", path, command.ID) + if seen[command.ID] { + return nil, fmt.Errorf("%s is listed twice", where) + } + seen[command.ID] = true + if strings.TrimSpace(command.Job) == "" { + return nil, fmt.Errorf("%s has no job", where) + } + if len(command.Argv) == 0 || command.Argv[0] == "" { + return nil, fmt.Errorf("%s has no argv", where) + } + if command.Cwd == "" { + file.Commands[i].Cwd = "." + } 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) + } + 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) + } + if commandEnvironmentForbidden(name) { + return nil, fmt.Errorf("%s: env may not set %s; collection never passes Datadog keys to repository code, and git values come from the checkout", where, name) + } + } + } + return file.Commands, nil +} + +// withCommandEnvironment runs fn with env applied to the process environment, as the command's job sets it, and +// with settings read again, so collection, its probes and the inventory's identity see the command's values. It +// restores the process environment and settings afterwards. +func withCommandEnvironment(env map[string]string, fn func() error) error { + if len(env) == 0 { + return fn() + } + previous := map[string]*string{} + for name, value := range env { + if old, exists := os.LookupEnv(name); exists { + previous[name] = &old + } else { + previous[name] = nil + } + _ = os.Setenv(name, value) + } + settings.Init() + defer func() { + for name, value := range previous { + if value == nil { + _ = os.Unsetenv(name) + } else { + _ = os.Setenv(name, *value) + } + } + settings.Init() + }() + return 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 { + return environ + } + result := make([]string, 0, len(environ)+len(env)) + for _, entry := range environ { + name, _, _ := strings.Cut(entry, "=") + if _, overridden := env[name]; !overridden { + result = append(result, entry) + } + } + for _, name := range slices.Sorted(maps.Keys(env)) { + result = append(result, name+"="+env[name]) + } + return result +} diff --git a/internal/selection/commands_test.go b/internal/selection/commands_test.go new file mode 100644 index 00000000..b07eb5ab --- /dev/null +++ b/internal/selection/commands_test.go @@ -0,0 +1,210 @@ +package selection + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DataDog/ddtest/internal/settings" + "github.com/DataDog/ddtest/internal/telemetry" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" +) + +const fixtureArgv = "./collector/python -m pytest tests/test_actual.py" + +func fixtureCommand(id, job string, env map[string]string) CallerCommand { + return CallerCommand{ID: id, Job: job, Argv: strings.Fields(fixtureArgv), Cwd: ".", Env: env} +} + +func writeCommandsFile(t *testing.T, path string, contents any) string { + t.Helper() + data, err := json.Marshal(contents) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data, 0644)) + return path +} + +func TestReadCommands(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-1", "job": "test (3.12)", "env_hash": "py312", "argv": []string{"pytest", "tests"}, "env": map[string]string{"DD_ENV": "ci"}}, + }})) + require.NoError(t, err) + require.Equal(t, []CallerCommand{{ID: "unit-1", Job: "test (3.12)", EnvHash: "py312", Argv: []string{"pytest", "tests"}, Cwd: ".", Env: map[string]string{"DD_ENV": "ci"}}}, commands) + + command := func(changes map[string]any) map[string]any { + value := map[string]any{"id": "unit", "job": "test", "argv": []string{"pytest"}} + for key, change := range changes { + value[key] = change + } + return value + } + for name, file := range map[string]map[string]any{ + "another schema version": {"schema_version": 2, "commands": []any{command(nil)}}, + "no commands": {"schema_version": 1, "commands": []any{}}, + "an id that is no file name": {"schema_version": 1, "commands": []any{command(map[string]any{"id": "../unit"})}}, + "the same id twice": {"schema_version": 1, "commands": []any{command(nil), command(nil)}}, + "no job": {"schema_version": 1, "commands": []any{command(map[string]any{"job": " "})}}, + "no argv": {"schema_version": 1, "commands": []any{command(map[string]any{"argv": []string{}})}}, + "a cwd outside": {"schema_version": 1, "commands": []any{command(map[string]any{"cwd": "../other"})}}, + "a bad variable name": {"schema_version": 1, "commands": []any{command(map[string]any{"env": map[string]string{"A-B": "1"}})}}, + "the API key": {"schema_version": 1, "commands": []any{command(map[string]any{"env": map[string]string{"DD_API_KEY": "key"}})}}, + "a git value": {"schema_version": 1, "commands": []any{command(map[string]any{"env": map[string]string{"DD_GIT_COMMIT_SHA": "abc"}})}}, + } { + t.Run(name, func(t *testing.T) { + _, err := ReadCommands(writeCommandsFile(t, "commands.json", file)) + require.Error(t, err) + }) + } + _, err = ReadCommands("missing.json") + require.ErrorContains(t, err, "read commands") +} + +// recordCommandEnvironment makes the collector fixture record COMMAND_FLAG in every process collection runs: the +// runtime probe, the packages probe and discovery. +func recordCommandEnvironment(t *testing.T) { + t.Helper() + collector, err := os.ReadFile("collector/python") + require.NoError(t, err) + recorded := strings.Replace(string(collector), "#!/bin/sh\n", "#!/bin/sh\nprintf '%s %s\\n' \"$1\" \"${COMMAND_FLAG-unset}\" >> environment.txt\n", 1) + require.NoError(t, os.WriteFile("collector/python", []byte(recorded), 0755)) +} + +func TestCollectCommandsAppliesEachCommandsEnvironment(t *testing.T) { + newSkippableBackend(t) + clearIdentityVariables(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "0") + recordCommandEnvironment(t) + commands := []CallerCommand{ + fixtureCommand("unit", "test (3.12)", map[string]string{"COMMAND_FLAG": "set-by-job", "DD_ENV": "staging"}), + fixtureCommand("integration", "integration", nil), + } + commands[0].EnvHash = "py312" + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, commands, "inventories", &output)) + + var collected []CollectedCommand + require.NoError(t, json.Unmarshal(output.Bytes(), &collected)) + require.Len(t, collected, 2) + require.Equal(t, "unit", collected[0].ID) + require.Equal(t, filepath.Join("inventories", "unit.json.gz"), collected[0].File) + + unit := readFixtureInventory(t, collected[0].File) + require.Equal(t, unit.Keys, collected[0].Keys) + require.Equal(t, "unit", unit.CommandID) + require.Equal(t, InventoryIdentity{Repo: unit.Identity.Repo, Commit: unit.Identity.Commit, Job: "test (3.12)", EnvHash: "py312", + Argv: strings.Fields(fixtureArgv), Cwd: ".", PytestConfig: unit.Identity.PytestConfig}, unit.Identity) + require.True(t, unit.Complete, unit.Errors) + require.Equal(t, "staging", unit.Datadog.Env) + require.Equal(t, map[string]string{"DD_ENV": "staging"}, unit.Datadog.Variables) + require.Equal(t, "sha256:"+sha256Hex([]byte("set-by-job")), unit.Inputs.Env["COMMAND_FLAG"]) + + integration := readFixtureInventory(t, collected[1].File) + require.Equal(t, "none", integration.Datadog.Env, "a command without env gets ddtest's own") + require.NotContains(t, integration.Inputs.Env, "COMMAND_FLAG") + require.NotEqual(t, unit.Keys.Environment, integration.Keys.Environment) + + seen, err := os.ReadFile("environment.txt") + require.NoError(t, err) + lines := strings.Split(strings.TrimSpace(string(seen)), "\n") + require.Contains(t, lines, "-c set-by-job", "the probes run with the command's env") + require.Contains(t, lines, "-m set-by-job", "discovery runs with the command's env") + require.Contains(t, lines, "-m unset") + _, exists := os.LookupEnv("COMMAND_FLAG") + require.False(t, exists, "the process environment is restored") + _, exists = os.LookupEnv("DD_ENV") + require.False(t, exists) +} + +func TestCollectCommandsChecksTheCommandsRuntimeTags(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "0") + // No --runtime-tags: an explicit setting would outrank the command's env, as the flag does. + viper.Reset() + settings.Init() + declared := strings.Replace(planRuntimeTags, "3.12.9", "3.13.0", 1) + commands := []CallerCommand{fixtureCommand("unit", "unit", map[string]string{"DD_TEST_OPTIMIZATION_RUNNER_RUNTIME_TAGS": declared})} + var output bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, commands, "inventories", &output)) + inventory := readFixtureInventory(t, filepath.Join("inventories", "unit.json.gz")) + require.False(t, inventory.Complete) + require.Contains(t, strings.Join(inventory.Errors, "; "), "3.13.0", "the declared runtime is checked against the interpreter that collects") + require.Empty(t, settings.GetRuntimeTags(), "settings are read again after the command") +} + +func TestCollectCommandsWritesNothingWhenOneFails(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "2") + viper.Set("strict_discovery", true) + settings.Init() + err := newFixtureSelector(t).CollectCommands(t.Context(), Options{}, []CallerCommand{fixtureCommand("unit", "unit", nil)}, "inventories", &bytes.Buffer{}) + require.ErrorContains(t, err, `command "unit"`) + _, statErr := os.Stat("inventories") + require.True(t, os.IsNotExist(statErr), "no inventory is written") +} + +func TestSelectCommands(t *testing.T) { + backend := newSkippableBackend(t) + clearIdentityVariables(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "0") + require.NoError(t, os.Mkdir("sub", 0755)) + outside := fixtureCommand("outside", "mixed", nil) + outside.Cwd = "sub" + commands := []CallerCommand{ + fixtureCommand("unit-a", "unit", map[string]string{"DD_ENV": "staging"}), + fixtureCommand("unit-b", "unit", nil), + fixtureCommand("mixed-a", "mixed", nil), + outside, + } + 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.Len(t, selection.Jobs, 2) + require.Equal(t, "unit", selection.Jobs[0].Name) + require.Equal(t, []string{"unit-a", "unit-b"}, selection.Jobs[0].Commands, "the caller's ids name the commands") + require.Equal(t, "skip", selection.Jobs[0].Decision) + require.Equal(t, "mixed", selection.Jobs[1].Name) + require.Equal(t, "run", selection.Jobs[1].Decision, "a job skips only when all its commands can") + require.Contains(t, selection.Commands[3].Reason, "repository root") + + environments := []string{} + for _, request := range backend.skippable { + environments = append(environments, request["data"].(map[string]any)["attributes"].(map[string]any)["env"].(string)) + } + require.ElementsMatch(t, []string{"staging", "none", "none"}, environments, "each command is asked about with its own identity") +} + +func TestSelectFromCollectedCommandsKeepsTheirIDs(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "0") + commands := []CallerCommand{fixtureCommand("unit-a", "unit", nil), fixtureCommand("unit-b", "unit", map[string]string{"COMMAND_FLAG": "b"})} + var collected bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, commands, "inventories", &collected)) + paths := []string{filepath.Join("inventories", "unit-a.json.gz"), filepath.Join("inventories", "unit-b.json.gz")} + for i, path := range paths { + absolute, err := filepath.Abs(path) + require.NoError(t, err) + paths[i] = absolute + } + leaveCheckout(t) + var output bytes.Buffer + require.NoError(t, SelectInventories(t.Context(), InventoryOptions{Inventories: paths, Output: "selection.json"}, &output, telemetry.NoopClient())) + var selection catalogSelection + require.NoError(t, json.Unmarshal(output.Bytes(), &selection)) + require.Equal(t, []string{"unit-a", "unit-b"}, selection.Jobs[0].Commands) +} diff --git a/internal/selection/decide.go b/internal/selection/decide.go index 49d5bdde..8dae3af4 100644 --- a/internal/selection/decide.go +++ b/internal/selection/decide.go @@ -148,11 +148,26 @@ func collectionChange(inventory Inventory, changed []string) string { return "" } -// commandIDs name a job's commands in the selection: the job alone for one command, otherwise the job and the start -// of the exact key of each command's contents. Contents a newer ddtest told apart by fields this one drops share -// that key, so those add the start of their stored key. +// commandIDs name a job's commands in the selection: the caller's names when it named each command differently, +// otherwise the job alone for one command, or the job and the start of the exact key of each command's contents. +// Contents a newer ddtest told apart by fields this one drops share that key, so those add the start of their +// stored key. func commandIDs(inventories []Inventory) []string { job := inventories[0].Identity.Job + named := map[string]int{} + for _, inventory := range inventories { + if inventory.CommandID != "" { + named[inventory.CommandID]++ + } + } + if len(named) == len(inventories) && !slices.ContainsFunc(slices.Collect(maps.Values(named)), func(count int) bool { return count > 1 }) { + // The caller named every command, each differently. + ids := make([]string, len(inventories)) + for i, inventory := range inventories { + ids[i] = inventory.CommandID + } + return ids + } if len(inventories) == 1 { return []string{job} } @@ -214,7 +229,9 @@ func decideCommand(ctx context.Context, job CatalogJob, command CatalogCommand, base, _ := decisionFramework(command.Framework) fw := planner.WithUnskippableFiles(base, command.UnskippableFiles) var selected planner.SuiteFileSelection - err := withRequestIdentity(identity, !checkout, func() error { + // The command's identity, which for live collection of one project command is the process's own, and for a + // commands file's command its job's. + err := withRequestIdentity(identity, true, func() error { var err error selected, err = planner.SelectDiscoveredSuiteTests(ctx, command.DiscoveredTests, fw, command.Configurations, plannerEnv, checkout, telemetryClient) return err diff --git a/internal/selection/inventory.go b/internal/selection/inventory.go index 98a74df2..f4b1919c 100644 --- a/internal/selection/inventory.go +++ b/internal/selection/inventory.go @@ -61,6 +61,9 @@ type Inventory struct { UnskippableFiles []string `json:"unskippable_files"` Counts InventoryCounts `json:"counts"` CasesSHA256 string `json:"cases_sha256"` + // CommandID is the caller's name for the command, from a commands file. The keys don't cover it: two commands + // that differ only in their names are the same command. + CommandID string `json:"command_id,omitempty"` } // InventoryIdentity is the command as CI runs it: the repository, the commit, the CI job and its environment hash, diff --git a/internal/selection/selection.go b/internal/selection/selection.go index 84969bc7..249c7601 100644 --- a/internal/selection/selection.go +++ b/internal/selection/selection.go @@ -89,6 +89,62 @@ func (s *Selector) Select(ctx context.Context, options Options, out io.Writer) e return write(out, options.Output, selection) } +// SelectCommands collects every command of a commands file, each with its job's env, decides which can skip, and +// writes the decisions to options.Output and to out. A job skips only when all its commands can. A failure leaves +// an existing output file unchanged. +func (s *Selector) SelectCommands(ctx context.Context, options Options, commands []CallerCommand, out io.Writer) error { + environ := collectionEnviron() + inventories := make([]Inventory, 0, len(commands)) + for _, command := range commands { + inventory, err := s.collectCallerCommand(ctx, options, command, environ) + if err != nil { + return fmt.Errorf("command %q: %w", command.ID, err) + } + inventories = append(inventories, inventory) + } + selection, err := decideInventories(ctx, inventories, true, nil, nil, s.telemetryClient) + if err != nil { + return err + } + return write(out, options.Output, selection) +} + +// CollectedCommand names one inventory CollectCommands wrote. +type CollectedCommand struct { + ID string `json:"id"` + Job string `json:"job"` + File string `json:"file"` + Keys InventoryKeys `json:"keys"` +} + +// CollectCommands collects every command of a commands file, each with its job's env, and writes one gzipped +// inventory per command to outputDir as .json.gz. It writes the list of inventories and their keys to out. It +// uploads git metadata as Collect does. A failure writes no inventory. +func (s *Selector) CollectCommands(ctx context.Context, options Options, commands []CallerCommand, outputDir string, out io.Writer) error { + environ := collectionEnviron() + uploaded, restore := startGitMetadataUpload() + defer restore() + inventories := make([]Inventory, 0, len(commands)) + for _, command := range commands { + inventory, err := s.collectCallerCommand(ctx, options, command, environ) + if err != nil { + waitGitMetadataUpload(uploaded) + return fmt.Errorf("command %q: %w", command.ID, err) + } + inventories = append(inventories, inventory) + } + waitGitMetadataUpload(uploaded) + collected := make([]CollectedCommand, 0, len(inventories)) + for _, inventory := range inventories { + file := filepath.Join(outputDir, inventory.CommandID+".json.gz") + if err := writeInventory(file, inventory); err != nil { + return err + } + collected = append(collected, CollectedCommand{ID: inventory.CommandID, Job: inventory.Identity.Job, File: file, Keys: inventory.Keys}) + } + return write(out, "", collected) +} + // Collect collects the project's test command, writes its inventory to options.Output as gzipped JSON, and // writes the inventory's keys to out. With a Datadog API key, it also uploads the checkout's git metadata, which // select needs and can't upload without the checkout; the collected command never gets the key. Without one, it From 232110f13fe85b3038d25b7dc53b0ea41df27bf4 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Fri, 4 Dec 2026 15:42:01 +0100 Subject: [PATCH 2/7] Read the platform environment again for each caller command, and allow identical commands with different ids The Python platform read PYTEST_ADDOPTS when it detected the framework, so discovery used ddtest's own options instead of a command's. Two listed commands with different ids but the same contents are two commands, not a duplicate. Co-Authored-By: Claude Opus 5.5 --- internal/platform/python_command.go | 6 +++++ internal/selection/collect.go | 10 +++++++- internal/selection/commands_test.go | 40 +++++++++++++++++++++++++++-- internal/selection/inventory.go | 5 ++-- 4 files changed, 56 insertions(+), 5 deletions(-) diff --git a/internal/platform/python_command.go b/internal/platform/python_command.go index 784c3a34..69a9c435 100644 --- a/internal/platform/python_command.go +++ b/internal/platform/python_command.go @@ -166,6 +166,12 @@ func (p *Python) CommandPackages(ctx context.Context, argv []string, framework, return packages, nil } +// 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() { + p.frameworkEnv = p.baseEnv() +} + // CommandLockFiles are the lock files a Python job may install from, as patterns relative to the repository root. func (p *Python) CommandLockFiles() []string { return []string{"uv.lock", "poetry.lock", "pdm.lock", "Pipfile.lock", "requirements*.txt"} diff --git a/internal/selection/collect.go b/internal/selection/collect.go index 8eaa0dd4..97d18ef4 100644 --- a/internal/selection/collect.go +++ b/internal/selection/collect.go @@ -38,6 +38,7 @@ type CommandPlatform interface { CommandConfigurations(ctx context.Context, argv []string) (map[string]string, error) CommandPackages(ctx context.Context, argv []string, framework, pluginGroup string) (platform.CommandPackages, error) CommandLockFiles() []string + ResetCommandEnvironment() FrameworkArguments(name string, argv []string) ([]string, bool) } @@ -69,10 +70,17 @@ func (s *Selector) collectProjectCommand(ctx context.Context, options Options, e return s.collectCommand(ctx, options, command, environ) } -// collectCallerCommand collects one command of a commands file, with its env applied as its job sets it. +// collectCallerCommand collects one command of a commands file, with its env applied as its job sets it. The +// platform reads its environment again, since it read it when it detected the framework. func (s *Selector) collectCallerCommand(ctx context.Context, options Options, command CallerCommand, environ []string) (Inventory, error) { + reset := func() {} + if commandPlatform, ok := s.platform.(CommandPlatform); ok { + reset = commandPlatform.ResetCommandEnvironment + } + defer reset() var inventory Inventory err := withCommandEnvironment(command.Env, func() error { + reset() var err error inventory, err = s.collectCommand(ctx, options, command, overlayEnviron(environ, command.Env)) return err diff --git a/internal/selection/commands_test.go b/internal/selection/commands_test.go index b07eb5ab..824881f1 100644 --- a/internal/selection/commands_test.go +++ b/internal/selection/commands_test.go @@ -70,7 +70,8 @@ func recordCommandEnvironment(t *testing.T) { t.Helper() collector, err := os.ReadFile("collector/python") require.NoError(t, err) - recorded := strings.Replace(string(collector), "#!/bin/sh\n", "#!/bin/sh\nprintf '%s %s\\n' \"$1\" \"${COMMAND_FLAG-unset}\" >> environment.txt\n", 1) + recorded := strings.Replace(string(collector), "#!/bin/sh\n", "#!/bin/sh\nprintf '%s %s\\n' \"$1\" \"${COMMAND_FLAG-unset}\" >> environment.txt\n"+ + "[ \"$1\" = -c ] || printf '%s\\n' \"$PYTEST_ADDOPTS\" >> addopts.txt\n", 1) require.NoError(t, os.WriteFile("collector/python", []byte(recorded), 0755)) } @@ -81,8 +82,10 @@ func TestCollectCommandsAppliesEachCommandsEnvironment(t *testing.T) { planTestSettings(t) installCommandCollector(t, "0") recordCommandEnvironment(t) + // ddtest's own PYTEST_ADDOPTS is read when the framework is detected, before any command's env applies. + t.Setenv("PYTEST_ADDOPTS", "-m unit") commands := []CallerCommand{ - fixtureCommand("unit", "test (3.12)", map[string]string{"COMMAND_FLAG": "set-by-job", "DD_ENV": "staging"}), + fixtureCommand("unit", "test (3.12)", map[string]string{"COMMAND_FLAG": "set-by-job", "DD_ENV": "staging", "PYTEST_ADDOPTS": "-m integration"}), fixtureCommand("integration", "integration", nil), } commands[0].EnvHash = "py312" @@ -116,6 +119,14 @@ func TestCollectCommandsAppliesEachCommandsEnvironment(t *testing.T) { require.Contains(t, lines, "-c set-by-job", "the probes run with the command's env") require.Contains(t, lines, "-m set-by-job", "discovery runs with the command's env") require.Contains(t, lines, "-m unset") + addopts, err := os.ReadFile("addopts.txt") + require.NoError(t, err) + discovered := strings.Split(strings.TrimSpace(string(addopts)), "\n") + require.Len(t, discovered, 2) + require.True(t, strings.HasPrefix(discovered[0], "-m integration "), "discovery runs with the command's PYTEST_ADDOPTS: %q", discovered[0]) + require.True(t, strings.HasPrefix(discovered[1], "-m unit "), "a command without its own keeps ddtest's: %q", discovered[1]) + require.Contains(t, discovered[0], "--ddtrace") + require.Contains(t, discovered[0], "--collect-only") _, exists := os.LookupEnv("COMMAND_FLAG") require.False(t, exists, "the process environment is restored") _, exists = os.LookupEnv("DD_ENV") @@ -187,6 +198,31 @@ func TestSelectCommands(t *testing.T) { require.ElementsMatch(t, []string{"staging", "none", "none"}, environments, "each command is asked about with its own identity") } +func TestSelectCommandsAllowsIdenticalCommandsWithDifferentIDs(t *testing.T) { + newSkippableBackend(t) + planRepositoryFixture(t) + planTestSettings(t) + installCommandCollector(t, "0") + commands := []CallerCommand{fixtureCommand("first", "unit", nil), fixtureCommand("second", "unit", nil)} + 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, []string{"first", "second"}, selection.Jobs[0].Commands) + + var collected bytes.Buffer + require.NoError(t, newFixtureSelector(t).CollectCommands(t.Context(), Options{}, commands, "inventories", &collected)) + first, err := filepath.Abs(filepath.Join("inventories", "first.json.gz")) + require.NoError(t, err) + second, err := filepath.Abs(filepath.Join("inventories", "second.json.gz")) + require.NoError(t, err) + leaveCheckout(t) + _, err = selectFromInventories(t, first, second) + require.NoError(t, err, "select --inventory takes both") + _, err = selectFromInventories(t, first, first) + require.ErrorContains(t, err, "the same command", "the same inventory twice is still an error") +} + func TestSelectFromCollectedCommandsKeepsTheirIDs(t *testing.T) { newSkippableBackend(t) planRepositoryFixture(t) diff --git a/internal/selection/inventory.go b/internal/selection/inventory.go index f4b1919c..3fbbd67e 100644 --- a/internal/selection/inventory.go +++ b/internal/selection/inventory.go @@ -388,12 +388,13 @@ func selectionCommit(inventories []Inventory) (string, error) { return "", fmt.Errorf("inventories name different repositories: %q and %q", first.Identity.Repo, inventory.Identity.Repo) } // The stored keys may be missing or stale, and a newer ddtest's keys cover fields this one drops, so an - // inventory is the same command as another only when both its contents and its stored keys say so. + // inventory is the same command as another only when both its contents and its stored keys say so, and the + // caller didn't name the two differently. keys, err := inventory.computeKeys() if err != nil { return "", fmt.Errorf("job %q: compute the inventory's keys: %w", inventory.Identity.Job, err) } - identity := keys.Exact + "/" + inventory.Keys.Exact + identity := keys.Exact + "/" + inventory.Keys.Exact + "/" + inventory.CommandID if exact[identity] { return "", fmt.Errorf("job %q: the same command is in more than one inventory", inventory.Identity.Job) } From 0bd37580c13374f7e8c281b92f049fdb836da5a6 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Fri, 4 Dec 2026 15:52:11 +0100 Subject: [PATCH 3/7] Compare commands-file env names and ids without case Windows compares variable names without case, so dd_api_key would set DD_API_KEY there; case-insensitive filesystems give Unit and unit the same inventory file. Co-Authored-By: Claude Opus 5.5 --- docs/running.md | 4 ++-- internal/selection/commands.go | 11 +++++++---- internal/selection/commands_test.go | 3 +++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/running.md b/docs/running.md index cd3be369..ef88b338 100644 --- a/docs/running.md +++ b/docs/running.md @@ -1008,7 +1008,7 @@ ddtest select --inventory inventories/unit-py312.json.gz --inventory inventories A command uses the field names of an inventory's identity, so a commands file is the inventories before collection: - `id` names the command in the selection, and its inventory file, `.json.gz`. It is letters, digits, `.`, `_` - and `-`, and is unique in the file. + and `-`, and is unique in the file, ignoring case. - `job` is the CI job the command belongs to. Commands with the same `job` are that job's commands, and the job skips only when all of them can. - `env_hash` is the job's environment hash, as `collect --env-hash` takes it. Optional. @@ -1018,7 +1018,7 @@ A command uses the field names of an inventory's identity, so a commands file is runtime and package probes, the identity Datadog is asked about and the inventory's environment hashes all see them, as the job would run the command. Runtime tags a command's `env` declares, such as `DD_TEST_OPTIMIZATION_RUNNER_RUNTIME_TAGS`, are checked against the interpreter that collects, as `--runtime-tags` - are; `--runtime-tags` wins over them. `env` may not set `DD_API_KEY`, `DD_APP_KEY` or `DD_GIT_*`: collection never + are; `--runtime-tags` wins over them. `env` may not set `DD_API_KEY`, `DD_APP_KEY` or `DD_GIT_*`, in any case: collection never passes Datadog keys to repository code, and git values come from the checkout. With `--commands`, `select` and `collect` take no `--command` or test patterns, and `collect` takes `--output-dir` diff --git a/internal/selection/commands.go b/internal/selection/commands.go index 8dbb2251..d7ccf05c 100644 --- a/internal/selection/commands.go +++ b/internal/selection/commands.go @@ -40,8 +40,10 @@ var commandIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) var variableNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) // commandEnvironmentForbidden are variables a command's env may not set: Datadog keys, which collection never -// passes to repository code, and git values, which come from the checkout. +// passes to repository code, and git values, which come from the checkout. Names compare without case, as Windows +// compares them. func commandEnvironmentForbidden(name string) bool { + name = strings.ToUpper(name) return name == "DD_API_KEY" || name == "DD_APP_KEY" || strings.HasPrefix(name, "DD_GIT_") } @@ -68,10 +70,11 @@ func ReadCommands(path string) ([]CallerCommand, error) { return nil, fmt.Errorf("%s: id %q must be letters, digits, '.', '_' or '-', starting with a letter or digit", where, command.ID) } where = fmt.Sprintf("commands %s: command %q", path, command.ID) - if seen[command.ID] { - return nil, fmt.Errorf("%s is listed twice", where) + // IDs name inventory files, so they compare without case, as case-insensitive filesystems compare names. + if seen[strings.ToLower(command.ID)] { + return nil, fmt.Errorf("%s is listed twice, ignoring case", where) } - seen[command.ID] = true + seen[strings.ToLower(command.ID)] = true if strings.TrimSpace(command.Job) == "" { return nil, fmt.Errorf("%s has no job", where) } diff --git a/internal/selection/commands_test.go b/internal/selection/commands_test.go index 824881f1..9d638b73 100644 --- a/internal/selection/commands_test.go +++ b/internal/selection/commands_test.go @@ -48,6 +48,9 @@ func TestReadCommands(t *testing.T) { "no commands": {"schema_version": 1, "commands": []any{}}, "an id that is no file name": {"schema_version": 1, "commands": []any{command(map[string]any{"id": "../unit"})}}, "the same id twice": {"schema_version": 1, "commands": []any{command(nil), command(nil)}}, + "ids that differ in case": {"schema_version": 1, "commands": []any{command(nil), command(map[string]any{"id": "Unit"})}}, + "the API key in lowercase": {"schema_version": 1, "commands": []any{command(map[string]any{"env": map[string]string{"dd_api_key": "key"}})}}, + "a git value in mixed case": {"schema_version": 1, "commands": []any{command(map[string]any{"env": map[string]string{"Dd_Git_Branch": "main"}})}}, "no job": {"schema_version": 1, "commands": []any{command(map[string]any{"job": " "})}}, "no argv": {"schema_version": 1, "commands": []any{command(map[string]any{"argv": []string{}})}}, "a cwd outside": {"schema_version": 1, "commands": []any{command(map[string]any{"cwd": "../other"})}}, From 3f16b33ebec3de546299bf528b84a7d36e0fb814 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Fri, 4 Dec 2026 15:58:48 +0100 Subject: [PATCH 4/7] Collect commands inside a repository runner's environment A command in a commands file can name the runner environment it runs in, as runner: {suite, environment, invocation, args}. Collection lists the runner's environments through its TestRunner, finds the command the referenced one runs, and has the runner run ddtest's worker in that command's place, so the runner prepares the environment itself. The worker probes the interpreter the command runs, with the probe command PythonProbeCommand gives for it, records the identity and skipping controls the runner sets for the command, and collects the command with --ddtrace and --collect-only added to the runner's PYTEST_ADDOPTS. The inventory records that interpreter's runtime and packages and the runner's identity, and names the runner environment in its identity. The measured runtime is checked against the environment's declared Python before any runtime tags apply. The listing checks the runner's interface by loading it, bounds its output without a ReadFrom path, and sets a WaitDelay. Co-Authored-By: Claude Opus 5.5 --- docs/running.md | 34 ++ internal/platform/python.go | 10 +- internal/platform/python_command.go | 66 +++- internal/platform/python_command_test.go | 35 ++ internal/platform/python_launchers.go | 10 + internal/selection/collect.go | 73 +++- internal/selection/commands.go | 53 ++- internal/selection/inventory.go | 5 +- internal/selection/python_runner.go | 311 +++++++++++++++ internal/selection/python_runner_test.go | 353 ++++++++++++++++++ internal/selection/runner.go | 107 ++++++ internal/selection/scripts/python_runner.py | 47 +++ .../scripts/python_runner_catalog.py | 21 ++ .../scripts/python_runner_collection.py | 25 ++ .../selection/scripts/python_runner_worker.py | 27 ++ internal/selection/selection.go | 2 + 16 files changed, 1155 insertions(+), 24 deletions(-) create mode 100644 internal/selection/python_runner.go create mode 100644 internal/selection/python_runner_test.go create mode 100644 internal/selection/runner.go create mode 100644 internal/selection/scripts/python_runner.py create mode 100644 internal/selection/scripts/python_runner_catalog.py create mode 100644 internal/selection/scripts/python_runner_collection.py create mode 100644 internal/selection/scripts/python_runner_worker.py diff --git a/docs/running.md b/docs/running.md index ef88b338..b011117c 100644 --- a/docs/running.md +++ b/docs/running.md @@ -1026,6 +1026,40 @@ 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`. + +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/platform/python.go b/internal/platform/python.go index d4497726..8c324e4c 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 69a9c435..d19754ba 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 50cd8495..99fc1888 100644 --- a/internal/platform/python_command_test.go +++ b/internal/platform/python_command_test.go @@ -280,3 +280,38 @@ func TestPythonPackagesScriptListsDistributionsAndPlugins(t *testing.T) { require.Contains(t, distribution, "==") } } + +func TestPythonEnvironmentProbeCommand(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + for _, tc := range []struct { + argv []string + want []string + }{ + {[]string{"pytest", "tests"}, []string{"python"}}, + {[]string{"python3.12", "-X", "dev", "-m", "pytest"}, []string{"python3.12", "-X", "dev"}}, + {[]string{"uv", "run", "pytest"}, []string{"uv", "run", "--no-sync", "python"}}, + } { + interpreter, prefix, err := PythonEnvironmentProbeCommand(tc.argv[0], tc.argv[1:]) + require.NoError(t, err, tc.argv) + require.Equal(t, tc.want, append([]string{interpreter}, prefix...), "the environment's pytest runs the environment's python, without one on ddtest's PATH") + } + _, _, 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 2f405986..25d629ae 100644 --- a/internal/platform/python_launchers.go +++ b/internal/platform/python_launchers.go @@ -171,6 +171,16 @@ 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 +// activate itself, such as the one a repository runner prepares: there, a pytest found on PATH is the environment's +// own, and runs the environment's python, as inside `uv run`. +func PythonEnvironmentProbeCommand(command string, args []string) (string, []string, error) { + if !strings.ContainsAny(command, `/\`) && strings.TrimSuffix(command, ".exe") == "pytest" { + return "python" + filepath.Ext(command), nil, nil + } + return PythonProbeCommand(command, args) +} + // 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 97d18ef4..86408426 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)...) + } + 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,60 @@ 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) []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.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 d7ccf05c..3fc667e3 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/inventory.go b/internal/selection/inventory.go index 3fbbd67e..a2d3a9e5 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 00000000..57035880 --- /dev/null +++ b/internal/selection/python_runner.go @@ -0,0 +1,311 @@ +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, shellquote.Split) + 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 + // A descendant that keeps the output pipes open must not hold the listing past its exit or its timeout. + cmd.WaitDelay = pythonRunnerListingWaitDelay + if err := cmd.Run(); 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"` + 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. + interpreter, prefix, err := platform.PythonEnvironmentProbeCommand(invocation.Argv[0], invocation.Argv[1:]) + if err != nil { + return runnerCollection{}, err + } + probe := append([]string{interpreter}, prefix...) + 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(probe), file("worker.py"), file("selection.json"))...), + DiscoveryVariables: slices.Sorted(maps.Keys(discovery.BaseEnv())), + Command: invocation.Command, Probe: probe, + 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; discovery adds only its own variables, which the + // collection script passes on to the worker. + tests, err := discovery.DiscoverCommand(ctx, r.executor, launcher, []string{file("collect.py"), file("selection.json")}, nil) + 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 00000000..3db5826a --- /dev/null +++ b/internal/selection/python_runner_test.go @@ -0,0 +1,353 @@ +package selection + +import ( + "bytes" + "encoding/json" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/DataDog/ddtest/internal/settings" + "github.com/kballard/go-shellquote" + "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") + 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"),))], + } + + 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: the host's, recording each call. +const fakeEnvironmentPython = "#!/bin/sh\nprintf '%s\\n' \"$1\" >> python-calls.txt\nexec python3 \"$@\"\n" + +// fakeEnvironmentPytest is the environment's pytest: it records what it collects with and reports one test. +const fakeEnvironmentPytest = `#!/bin/sh +printf '%s\n' "$PYTEST_ADDOPTS" > addopts.txt +printf '%s\n' "${COMMAND_FLAG-unset}" > command-flag.txt +printf '%s\n' "$@" > arguments.txt +cat identities.json > "$DD_TEST_OPTIMIZATION_DISCOVERY_FILE" +` + +// 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) + for _, file := range []string{"scripts/run-tests", "scripts/uv-run-script", "env/bin/python", "env/bin/pytest"} { + 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") + 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) + + calls := readLines(t, "python-calls.txt") + require.Contains(t, calls, "-c", "the environment's python is probed") + 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 '{\"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") +} + +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) { + words, ok := commandWords("pytest -v --ignore-glob='civisibility' tests/integration/", shellquote.Split) + require.True(t, ok) + require.Equal(t, []string{"pytest", "-v", "--ignore-glob=civisibility", "tests/integration/"}, words) + for _, command := range []string{"pytest a && pytest b", "pytest a; pytest b", "pytest $TESTS", "pytest tests/*.py", "pytest > out", "", "pytest 'unterminated"} { + _, ok := commandWords(command, shellquote.Split) + 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") +} diff --git a/internal/selection/runner.go b/internal/selection/runner.go new file mode 100644 index 00000000..005708ba --- /dev/null +++ b/internal/selection/runner.go @@ -0,0 +1,107 @@ +package selection + +import ( + "bytes" + "context" + "fmt" + "strings" + + "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 make a runner's command line more than one command, or let the shell change +// the words it runs. +const shellSyntax = ";&|<>`$(){}*?[]~!#\n" + +// 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. +func commandWords(command string, split func(string) ([]string, error)) ([]string, bool) { + if strings.ContainsAny(command, shellSyntax) { + return nil, false + } + words, err := 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 00000000..a4b289c5 --- /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 00000000..a537ab2d --- /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 00000000..8fa5dfc6 --- /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 00000000..d790285d --- /dev/null +++ b/internal/selection/scripts/python_runner_worker.py @@ -0,0 +1,27 @@ +"""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 probes the Python the command runs, records the variables +the command would see, and runs the command for collection only. +""" + +import json +import os +import subprocess +import sys + +with open(sys.argv[1]) as stream: + selection = json.load(stream) + +probe = selection["probe"] +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"]] +) +# 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() +os.execvp("bash", ["bash", "-c", selection["command"]]) diff --git a/internal/selection/selection.go b/internal/selection/selection.go index 249c7601..382c4ab1 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. From 9fe6afb438c79f86f23608f108ea22d32e6df14e Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Fri, 4 Dec 2026 16:40:49 +0100 Subject: [PATCH 5/7] Resolve runner collection's service, keys, entry points and quoting - Record the service the runner gives the command, read while its variables apply, so an inventory whose runner sets DD_SERVICE can skip. - Give the runner no Datadog keys: the listing and collection see the placeholder DD_API_KEY and no DD_APP_KEY. - Find the interpreter a pytest entry point runs inside the prepared environment, from the entry point's own script, including the wrapper uv writes for a relocatable environment. - Read quoted characters in a runner's command as literals, so options such as --ignore-glob='*civisibility*' don't make it a shell program. - Decide a runner inventory only for its own commit: the runner's definitions, wherever the repository keeps them, decide what it collects. Co-Authored-By: Claude Opus 5.5 --- docs/running.md | 8 +- internal/platform/python_command_test.go | 14 ++- internal/platform/python_launchers.go | 16 ++-- internal/selection/collect.go | 5 +- internal/selection/decide.go | 5 +- internal/selection/python_runner.go | 29 ++++-- internal/selection/python_runner_test.go | 93 ++++++++++++++++--- internal/selection/runner.go | 44 +++++++-- .../selection/scripts/python_runner_worker.py | 35 ++++++- 9 files changed, 201 insertions(+), 48 deletions(-) diff --git a/docs/running.md b/docs/running.md index b011117c..43b9f6a1 100644 --- a/docs/running.md +++ b/docs/running.md @@ -1052,7 +1052,13 @@ skipping controls that the runner sets for the command, in place of ddtest's own - 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`. +- 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 diff --git a/internal/platform/python_command_test.go b/internal/platform/python_command_test.go index 99fc1888..c4ca8b12 100644 --- a/internal/platform/python_command_test.go +++ b/internal/platform/python_command_test.go @@ -283,19 +283,25 @@ func TestPythonPackagesScriptListsDistributionsAndPlugins(t *testing.T) { 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{"pytest", "tests"}, []string{"python"}}, {[]string{"python3.12", "-X", "dev", "-m", "pytest"}, []string{"python3.12", "-X", "dev"}}, {[]string{"uv", "run", "pytest"}, []string{"uv", "run", "--no-sync", "python"}}, } { - interpreter, prefix, err := PythonEnvironmentProbeCommand(tc.argv[0], tc.argv[1:]) + interpreter, prefix, entryPoint, err := PythonEnvironmentProbeCommand(tc.argv[0], tc.argv[1:]) require.NoError(t, err, tc.argv) - require.Equal(t, tc.want, append([]string{interpreter}, prefix...), "the environment's pytest runs the environment's python, without one on ddtest's PATH") + require.Empty(t, entryPoint) + require.Equal(t, tc.want, append([]string{interpreter}, prefix...)) } - _, _, err := PythonEnvironmentProbeCommand("tox", []string{"-e", "py312"}) + _, _, _, err := PythonEnvironmentProbeCommand("tox", []string{"-e", "py312"}) require.Error(t, err) } diff --git a/internal/platform/python_launchers.go b/internal/platform/python_launchers.go index 25d629ae..6912ce29 100644 --- a/internal/platform/python_launchers.go +++ b/internal/platform/python_launchers.go @@ -172,13 +172,15 @@ func PythonProbeCommand(command string, args []string) (string, []string, error) } // PythonEnvironmentProbeCommand is PythonProbeCommand for a command that runs inside an environment ddtest doesn't -// activate itself, such as the one a repository runner prepares: there, a pytest found on PATH is the environment's -// own, and runs the environment's python, as inside `uv run`. -func PythonEnvironmentProbeCommand(command string, args []string) (string, []string, error) { - if !strings.ContainsAny(command, `/\`) && strings.TrimSuffix(command, ".exe") == "pytest" { - return "python" + filepath.Ext(command), nil, nil - } - return PythonProbeCommand(command, args) +// 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 diff --git a/internal/selection/collect.go b/internal/selection/collect.go index 86408426..c5f5e643 100644 --- a/internal/selection/collect.go +++ b/internal/selection/collect.go @@ -143,7 +143,7 @@ func (s *Selector) collectCommand(ctx context.Context, options Options, command 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)...) + 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, "; ")) @@ -198,7 +198,7 @@ func (s *Selector) collectCommand(ctx context.Context, options Options, command // 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) []string { +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()} @@ -227,6 +227,7 @@ func (s *Selector) collectInRunner(ctx context.Context, inventory *Inventory, co 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...))) diff --git a/internal/selection/decide.go b/internal/selection/decide.go index 8dae3af4..0cb2e33a 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/python_runner.go b/internal/selection/python_runner.go index 57035880..c51e9cd5 100644 --- a/internal/selection/python_runner.go +++ b/internal/selection/python_runner.go @@ -111,7 +111,7 @@ func (r *pythonRunner) resolve(ctx context.Context, reference RunnerReference) ( } // 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, shellquote.Split) + argv, ok := commandWords(command) if !ok { return runnerInvocation{}, fmt.Errorf("runner command %q is a shell program; collection supports one framework command", command) } @@ -141,6 +141,9 @@ func (r *pythonRunner) listing(ctx context.Context) (pythonRunnerListing, error) 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. cmd.WaitDelay = pythonRunnerListingWaitDelay if err := cmd.Run(); err != nil { @@ -170,6 +173,7 @@ type pythonRunnerSelection struct { 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"` @@ -182,12 +186,18 @@ type pythonRunnerSelection struct { } 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. - interpreter, prefix, err := platform.PythonEnvironmentProbeCommand(invocation.Argv[0], invocation.Argv[1:]) + // 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 } - probe := append([]string{interpreter}, prefix...) + 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 @@ -199,9 +209,9 @@ func (r *pythonRunner) collect(ctx context.Context, invocation runnerInvocation, runtimeScript, packagesScript := platform.PythonProbeScripts() selection := pythonRunnerSelection{ Suite: invocation.Reference.Suite, Environment: invocation.Reference.Environment, - WorkerCommand: shellquote.Join(append(slices.Clone(probe), file("worker.py"), file("selection.json"))...), + 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, + 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(), @@ -216,9 +226,10 @@ func (r *pythonRunner) collect(ctx context.Context, invocation runnerInvocation, if err := os.WriteFile(file("selection.json"), data, 0600); err != nil { return runnerCollection{}, err } - // The runner runs with the command's whole environment; discovery adds only its own variables, which the - // collection script passes on to the worker. - tests, err := discovery.DiscoverCommand(ctx, r.executor, launcher, []string{file("collect.py"), file("selection.json")}, nil) + // 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 } diff --git a/internal/selection/python_runner_test.go b/internal/selection/python_runner_test.go index 3db5826a..6077a159 100644 --- a/internal/selection/python_runner_test.go +++ b/internal/selection/python_runner_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/DataDog/ddtest/internal/settings" - "github.com/kballard/go-shellquote" "github.com/spf13/viper" "github.com/stretchr/testify/require" ) @@ -57,6 +56,10 @@ class TestRunner: 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"), @@ -71,6 +74,8 @@ class TestRunner: "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): @@ -84,15 +89,28 @@ class TestRunner: return True ` -// fakeEnvironmentPython is the environment's python: the host's, recording each call. +// 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" -// fakeEnvironmentPytest is the environment's pytest: it records what it collects with and reports one test. +// 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 -printf '%s\n' "$PYTEST_ADDOPTS" > addopts.txt -printf '%s\n' "${COMMAND_FLAG-unset}" > command-flag.txt -printf '%s\n' "$@" > arguments.txt -cat identities.json > "$DD_TEST_OPTIMIZATION_DISCOVERY_FILE" +'''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. @@ -122,7 +140,8 @@ func installFakePythonRunner(t *testing.T) string { planTestFile(t, "scripts/uv-run-script", "#!/bin/sh\nexec python3 \"$@\"\n") planTestFile(t, "env/bin/python", fakeEnvironmentPython) planTestFile(t, "env/bin/pytest", fakeEnvironmentPytest) - for _, file := range []string{"scripts/run-tests", "scripts/uv-run-script", "env/bin/python", "env/bin/pytest"} { + 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) @@ -141,6 +160,7 @@ func TestCollectCommandsInARunnerEnvironment(t *testing.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"} @@ -161,8 +181,10 @@ func TestCollectCommandsInARunnerEnvironment(t *testing.T) { inventory.Datadog.Variables, "the identity is the one the runner gives the command") require.NotEmpty(t, inventory.Inputs.VenvSHA256) - calls := readLines(t, "python-calls.txt") - require.Contains(t, calls, "-c", "the environment's python is probed") + require.Contains(t, readLines(t, "entry-point-calls.txt"), "-c", "the interpreter the entry point names is probed") + _, 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") @@ -313,11 +335,18 @@ func TestInlineScriptMetadata(t *testing.T) { } func TestCommandWords(t *testing.T) { - words, ok := commandWords("pytest -v --ignore-glob='civisibility' tests/integration/", shellquote.Split) - require.True(t, ok) - require.Equal(t, []string{"pytest", "-v", "--ignore-glob=civisibility", "tests/integration/"}, words) - for _, command := range []string{"pytest a && pytest b", "pytest a; pytest b", "pytest $TESTS", "pytest tests/*.py", "pytest > out", "", "pytest 'unterminated"} { - _, ok := commandWords(command, shellquote.Split) + 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) } } @@ -351,3 +380,37 @@ func readLines(t *testing.T, path string) []string { 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 index 005708ba..50520511 100644 --- a/internal/selection/runner.go +++ b/internal/selection/runner.go @@ -6,6 +6,8 @@ import ( "fmt" "strings" + "github.com/kballard/go-shellquote" + "github.com/DataDog/ddtest/internal/platform" "github.com/DataDog/ddtest/internal/testoptimization" ) @@ -68,17 +70,43 @@ func runnerVersionMatches(measured, declared string) bool { return measured != "" && (measured == declared || strings.HasPrefix(measured, declared+".")) } -// shellSyntax are the characters that make a runner's command line more than one command, or let the shell change -// the words it runs. -const shellSyntax = ";&|<>`$(){}*?[]~!#\n" +// 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. -func commandWords(command string, split func(string) ([]string, error)) ([]string, bool) { - if strings.ContainsAny(command, shellSyntax) { - return nil, false +// 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 := split(command) + words, err := shellquote.Split(command) if err != nil || len(words) == 0 { return nil, false } diff --git a/internal/selection/scripts/python_runner_worker.py b/internal/selection/scripts/python_runner_worker.py index d790285d..9f910ce9 100644 --- a/internal/selection/scripts/python_runner_worker.py +++ b/internal/selection/scripts/python_runner_worker.py @@ -6,13 +6,46 @@ import json import os +import shutil import subprocess import sys with open(sys.argv[1]) as stream: selection = json.load(stream) -probe = selection["probe"] +# 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"])] 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"]] From 614dc52ed92560c6259806da7df30ff7ffd47ca8 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Sat, 5 Dec 2026 08:23:38 +0100 Subject: [PATCH 6/7] Probe a runner command after it runs, and stop the listing's descendants - The worker runs the command, then probes its interpreter, since the command may install dependencies as it starts, as uv run does: the inventory records the packages collection ran with. - The listing runs in its own process group, which a timeout kills, and what is left of the group is killed once the listing returns, so a descendant doesn't outlive it. Co-Authored-By: Claude Opus 5.5 --- internal/ext/command_process_other.go | 8 ++++++++ internal/ext/command_process_unix.go | 12 ++++++++++++ internal/ext/command_process_windows.go | 8 ++++++++ internal/selection/python_runner.go | 9 +++++++-- internal/selection/python_runner_test.go | 10 ++++++++-- .../selection/scripts/python_runner_worker.py | 17 ++++++++++------- 6 files changed, 53 insertions(+), 11 deletions(-) diff --git a/internal/ext/command_process_other.go b/internal/ext/command_process_other.go index 09b42129..4c8c4861 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 1b852f52..b89d879a 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 dc3b1c4a..63975b87 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/selection/python_runner.go b/internal/selection/python_runner.go index c51e9cd5..8e12138f 100644 --- a/internal/selection/python_runner.go +++ b/internal/selection/python_runner.go @@ -144,9 +144,14 @@ func (r *pythonRunner) listing(ctx context.Context) (pythonRunnerListing, error) // 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. + // 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 - if err := cmd.Run(); err != nil { + 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())) diff --git a/internal/selection/python_runner_test.go b/internal/selection/python_runner_test.go index 6077a159..5102a482 100644 --- a/internal/selection/python_runner_test.go +++ b/internal/selection/python_runner_test.go @@ -181,7 +181,10 @@ func TestCollectCommandsInARunnerEnvironment(t *testing.T) { inventory.Datadog.Variables, "the identity is the one the runner gives the command") require.NotEmpty(t, inventory.Inputs.VenvSHA256) - require.Contains(t, readLines(t, "entry-point-calls.txt"), "-c", "the interpreter the entry point names is probed") + 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") @@ -309,11 +312,14 @@ func TestRunnerListingIsBounded(t *testing.T) { require.ErrorContains(t, err, "runner listing exceeds 64 bytes") pythonRunnerListingWaitDelay = 100 * time.Millisecond - planTestFile(t, "scripts/uv-run-script", "#!/bin/sh\nsleep 30 &\necho '{\"suites\":[]}'\n") + 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] + require.Eventually(t, func() bool { return exec.Command("kill", "-0", pid).Run() != nil }, 5*time.Second, 50*time.Millisecond, + "the descendant doesn't outlive the listing") } func TestCappedOutputHasNoReadFrom(t *testing.T) { diff --git a/internal/selection/scripts/python_runner_worker.py b/internal/selection/scripts/python_runner_worker.py index 9f910ce9..5b132e5d 100644 --- a/internal/selection/scripts/python_runner_worker.py +++ b/internal/selection/scripts/python_runner_worker.py @@ -1,7 +1,7 @@ """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 probes the Python the command runs, records the variables -the command would see, and runs the command for collection only. +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 @@ -46,10 +46,6 @@ def entry_point_interpreter(entry_point): probe = selection["probe"] or [entry_point_interpreter(selection["entry_point"])] -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"]] -) # 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: @@ -57,4 +53,11 @@ def entry_point_interpreter(entry_point): # 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() -os.execvp("bash", ["bash", "-c", selection["command"]]) +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"]] +) From de64ad9eb53622b6f2cb9b6bec5cb8eba64e5b59 Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Sat, 5 Dec 2026 11:26:24 +0100 Subject: [PATCH 7/7] Count a zombie as gone in the listing cleanup test Where nothing reaps orphans, as in some containers, the killed descendant stays a zombie, which kill -0 still reports as alive. Co-Authored-By: Claude Opus 5.5 --- internal/selection/python_runner_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/internal/selection/python_runner_test.go b/internal/selection/python_runner_test.go index 5102a482..2376d5d3 100644 --- a/internal/selection/python_runner_test.go +++ b/internal/selection/python_runner_test.go @@ -318,8 +318,11 @@ func TestRunnerListingIsBounded(t *testing.T) { 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] - require.Eventually(t, func() bool { return exec.Command("kill", "-0", pid).Run() != nil }, 5*time.Second, 50*time.Millisecond, - "the descendant doesn't outlive the listing") + // 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) {