From de93e29f9caaa453aef786cf3cf9dde2f6d442fb Mon Sep 17 00:00:00 2001 From: Petr Malik Date: Mon, 9 Nov 2026 17:41:54 -0500 Subject: [PATCH] feat: Add persistent host directory mounts Allow services, tools, and custom validators to mount operator-owned host directories into their Docker containers. Mounts are read-only unless marked writable, and relative sources resolve beside config.yaml. ``` bind-mounts: - source: ./exports target: /exports writable: true ``` Before any task starts, the runner verifies that each mount source used by the selected tasks exists and is a directory. Unused definitions are not checked. Sources are checked again when containers are created. Mount targets must not overlap other mounts in the same container, including tool shared, auxiliary, and parameter-file paths. Service-input templates can use `{{ .Service.InstanceID }}` to create a unique per-instance export directory, including across retries. --- .github/workflows/go.yml | 5 + README.md | 24 ++- config/bind_mounts.go | 113 ++++++++++++++ config/bind_mounts_test.go | 74 +++++++++ config/config.go | 6 + config/services_test.go | 198 ++++++++++++++++++++++++ config/utils.go | 4 + config/utils_test.go | 24 +++ pkg/testutils/docker.go | 16 +- providers/tools/bind_mounts.go | 29 ++++ providers/tools/bind_mounts_test.go | 180 +++++++++++++++++++++ providers/tools/docker_executor.go | 11 +- providers/tools/docker_executor_test.go | 11 +- providers/tools/docker_helpers.go | 13 ++ providers/tools/task_runtime.go | 44 +++++- providers/tools/task_runtime_test.go | 118 ++++++++++++-- runners/bind_mounts_test.go | 137 ++++++++++++++++ runners/default_runner.go | 14 +- validators/custom_validator.go | 1 + validators/custom_validator_test.go | 13 +- 20 files changed, 1004 insertions(+), 31 deletions(-) create mode 100644 config/bind_mounts.go create mode 100644 config/bind_mounts_test.go create mode 100644 providers/tools/bind_mounts.go create mode 100644 providers/tools/bind_mounts_test.go create mode 100644 runners/bind_mounts_test.go diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index 5417192..4fac56a 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -37,5 +37,10 @@ jobs: - name: Build run: go build -v ./... + - name: Load service shutdown smoke image + run: docker pull busybox@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662 + - name: Test + env: + MINDTRIAL_TEST_BUSYBOX_IMAGE: busybox@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662 run: go test -tags=test -race -v ./... diff --git a/README.md b/README.md index 1a038a4..c41b25c 100644 --- a/README.md +++ b/README.md @@ -1292,6 +1292,7 @@ Tools must be defined in `config.yaml` under the `tools` section. Each tool defi - **parameter-files**: Mapping of parameter names to container file paths where argument values should be written. Argument values are converted to strings, non-string values are marshaled to JSON. The tool's command should read these files as needed. - **auxiliary-dir**: Directory path inside the container where task files with `local` access will be automatically mounted. If specified, files with `local` access attached to the task will be mounted to this directory using each file's unique reference `name` exactly as provided. Files in this directory are reset between tool calls. - **shared-dir**: Directory path inside the container that persists across all tool calls within a single task. If specified, files created in this directory will be available for any subsequent tool calls but will be removed when the task completes. +- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this tool only (optional). - **command**: Command to run inside the container. The standard output of the command execution is captured and passed back to the LLM as is. - **env**: Environment variables to set in the container. - **dependencies**: [Task services](#task-services) the tool can access, each with a `service` name and optional `env` [templates](#templates). @@ -1422,6 +1423,7 @@ Services are defined in `config.yaml` under the `services` section: - **name**: A unique name for the service, used in `dependencies` and `service-inputs`. - **image**: Docker image used to run the service. +- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this service only (optional). - **command**: Command overriding the image's default command (optional). - **env**: Environment variables set for every instance of the service (optional). - **endpoint**: Where tools and validators connect to the service. @@ -1477,6 +1479,7 @@ Validators are defined in `config.yaml` under the `validators` section: - **name**: A unique name for the validator, used by `custom-validator` in task validation rules. - **image**: Docker image used to run the validator. +- **bind-mounts**: [Operator-owned host directories](#persistent-host-directories) attached to this validator only (optional). - **command**: Command overriding the image's default command (optional). Each argument is a [template](#templates) and is passed directly to Docker, without a shell. - **env**: Environment variables set in the validator container (optional). Each value is a [template](#templates). - **template-files**: Files created for each validation and mounted read-only into the validator container (optional). @@ -1549,6 +1552,24 @@ The object must match this schema: Results checked by a custom validator record `custom` as their validation method. Failed answers are shown exactly as the model returned them, without a comparison against `expected-result`. Validator runs are not counted as model tool calls. +#### Persistent host directories + +Set `bind-mounts` on a **service**, **tool**, or **custom validator** in the operator’s `config.yaml`. Use this to collect files after a container is removed, or to give one container read-only access to existing inputs. For scratch space shared by tool calls and deleted at task completion, keep using `shared-dir`. + +```yaml +# In one service, tool, or custom validator definition: +bind-mounts: + - source: ./exports # Create this directory beside config.yaml before running. + target: /exports # Absolute path in the container. + writable: true # Omit for read-only access. +``` + +The source must already be a directory accessible to both MindTrial and the Docker daemon at the resolved path. Relative sources resolve beside `config.yaml`, regardless of where you launch MindTrial. They are literal operator paths, never task or model templates. MindTrial does not create, chmod, relabel, empty, or delete the host directory. The configured image must have the needed filesystem permissions; files keep the writer’s UID and permissions. On SELinux hosts, provide a dedicated directory with an appropriate container-accessible label. Do not expose private exports to a model-controlled tool. Targets must not overlap other configured mounts in the same container. + +Every container with the same writable source can see or overwrite the same data, including on retries. For independent service exports, mount a pre-existing **parent** and have the service create one child per instance. For example, declare `input-env: {output: APP_OUTPUT_DIR}` on the service; in `tool-selector.service-inputs` set its `output` to `"/exports/{{ .Service.InstanceID }}"`. The generated service container name is unique across retries and appears in the DEBUG log alongside the task trace. Only explicitly configured containers see the mount; a network dependency does not inherit it. + +At normal teardown MindTrial asks a ready service to stop before reading its final logs and removing it. It gives the service up to 10 seconds to flush; a crash or forced stop can still leave partial files. + #### Templates Service inputs, dependency environment variables, and custom validator settings use Go template syntax. MindTrial checks template syntax before any task runs, and using a field that does not exist is an error. @@ -1557,12 +1578,13 @@ Each kind of template has its own fields: | Template | Available fields | | --- | --- | -| `service-inputs` string values | `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` | +| `service-inputs` string values | `.Service.InstanceID`, `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` | | `dependencies[].env` values | `.Name`, `.Host`, `.Port`, `.Endpoint` | | Validator `command`, `env`, and `template-files` | `.OriginalTask.*`, `.Candidate.Response`, `.Rules.*`, `.Evaluation.Seed`, `.Task.Name`, `.Provider.Name`, `.Run.Name` | Fields: +- **{{ .Service.InstanceID }}**: Generated service container name, unique to this service instance, including across retries. Available in service-input templates only. - **{{ .Evaluation.Seed }}**: Evaluation seed shared by all providers, runs, tasks, and attempts of one evaluation. - **{{ .Task.Name }}**, **{{ .Provider.Name }}**, **{{ .Run.Name }}**: Names of the task, the provider, and the run configuration. - **{{ .Name }}**: Name of the service. diff --git a/config/bind_mounts.go b/config/bind_mounts.go new file mode 100644 index 0000000..f5e9250 --- /dev/null +++ b/config/bind_mounts.go @@ -0,0 +1,113 @@ +// Copyright (C) 2026 Petr Malik +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +package config + +import ( + "fmt" + "os" + "path" + "path/filepath" + "strings" +) + +// BindMountConfig attaches an existing host directory. MindTrial never owns its contents. +type BindMountConfig struct { + // Source is the host directory, resolved relative to the configuration file when needed. + Source string `yaml:"source" validate:"required"` + // Target is the absolute, non-root path inside the container. + Target string `yaml:"target" validate:"required"` + // Writable permits writes to the host directory; mounts are read-only by default. + Writable bool `yaml:"writable,omitempty"` +} + +// ValidateSource checks that the resolved host source exists and is a directory. +// Callers should recheck at mount time because the filesystem may change after preflight. +func (c BindMountConfig) ValidateSource() error { + if !filepath.IsAbs(c.Source) { + return fmt.Errorf("%w: bind source %q is not an absolute host path", ErrInvalidConfigProperty, c.Source) + } + info, err := os.Stat(c.Source) + if err != nil { + return fmt.Errorf("%w: bind source %q: %w", ErrInvalidConfigProperty, c.Source, err) + } + if !info.IsDir() { + return fmt.Errorf("%w: bind source %q is not a directory", ErrInvalidConfigProperty, c.Source) + } + return nil +} + +// resolveBindMounts interprets relative sources against config.yaml, as with output-dir. +// Never expand task templates in host paths. Defer filesystem checks until preflight: an +// unrelated configured tool or service need not be available for this evaluation. +func (c *AppConfig) resolveBindMounts(configDir string) error { + for _, tool := range c.Tools { + if len(tool.BindMounts) == 0 { + continue + } + reserved := make([]string, 0, 2+len(tool.ParameterFiles)) + reserved = append(reserved, tool.SharedDir, tool.AuxiliaryDir) + for _, parameterPath := range tool.ParameterFiles { + reserved = append(reserved, parameterPath) + } + if err := resolveMounts(configDir, tool.BindMounts, reserved); err != nil { + return fmt.Errorf("tool %q: %w", tool.Name, err) + } + } + for _, service := range c.Services { + if err := resolveMounts(configDir, service.BindMounts, nil); err != nil { + return fmt.Errorf("service %q: %w", service.Name, err) + } + } + for _, validator := range c.Validators { + if len(validator.BindMounts) == 0 { + continue + } + var reserved []string + for _, file := range validator.TemplateFiles { + reserved = append(reserved, file.Path) + } + if err := resolveMounts(configDir, validator.BindMounts, reserved); err != nil { + return fmt.Errorf("validator %q: %w", validator.Name, err) + } + } + return nil +} + +func resolveMounts(configDir string, mounts []BindMountConfig, reserved []string) error { + for i := range mounts { + mount := &mounts[i] + if strings.TrimSpace(mount.Source) == "" || !path.IsAbs(mount.Target) || path.Clean(mount.Target) == "/" { + return fmt.Errorf("%w: bind-mounts[%d] needs a host source and an absolute non-root container target", ErrInvalidConfigProperty, i) + } + mount.Target = path.Clean(mount.Target) + for _, reservedPath := range reserved { + if reservedPath == "" { + continue + } + reservedPath = path.Clean(reservedPath) + if pathContains(reservedPath, mount.Target) || pathContains(mount.Target, reservedPath) { + return fmt.Errorf("%w: bind target %q overlaps container path %q", ErrInvalidConfigProperty, mount.Target, reservedPath) + } + } + source := mount.Source + if !filepath.IsAbs(source) { + source = filepath.Join(configDir, source) + } + absoluteSource, err := filepath.Abs(source) + if err != nil { + return fmt.Errorf("%w: bind source %q: %w", ErrInvalidConfigProperty, mount.Source, err) + } + mount.Source = absoluteSource + reserved = append(reserved, mount.Target) + } + return nil +} + +// pathContains compares cleaned POSIX paths at component boundaries. +func pathContains(parent string, child string) bool { + return parent == child || strings.HasPrefix(child, strings.TrimSuffix(parent, "/")+"/") +} diff --git a/config/bind_mounts_test.go b/config/bind_mounts_test.go new file mode 100644 index 0000000..5f4b502 --- /dev/null +++ b/config/bind_mounts_test.go @@ -0,0 +1,74 @@ +// Copyright (C) 2026 Petr Malik +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/petmal/mindtrial/pkg/testutils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBindMountConfigValidateSource(t *testing.T) { + directory := t.TempDir() + file := testutils.CreateMockFile(t, "bind-source-*.txt", []byte("keep")) + t.Cleanup(func() { assert.NoError(t, os.Remove(file)) }) + tests := []struct { + name string + source string + wantErr error + }{ + { + name: "directory", + source: directory, + }, + { + name: "missing directory", + source: filepath.Join(directory, "missing"), + wantErr: os.ErrNotExist, + }, + { + name: "file", + source: file, + wantErr: ErrInvalidConfigProperty, + }, + { + name: "relative source", + source: "relative", + wantErr: ErrInvalidConfigProperty, + }, + { + name: "empty source", + wantErr: ErrInvalidConfigProperty, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := (BindMountConfig{Source: tt.source}).ValidateSource() + if tt.wantErr != nil { + require.ErrorIs(t, err, ErrInvalidConfigProperty) + assert.ErrorIs(t, err, tt.wantErr) + return + } + require.NoError(t, err) + }) + } + assert.NoDirExists(t, filepath.Join(directory, "missing")) + assert.FileExists(t, file) +} + +func TestBindMountConfigValidateSourceRechecksDirectory(t *testing.T) { + source := filepath.Join(t.TempDir(), "source") + require.NoError(t, os.Mkdir(source, 0o700)) + mount := BindMountConfig{Source: source} + require.NoError(t, mount.ValidateSource()) + require.NoError(t, os.Remove(source)) + require.ErrorIs(t, mount.ValidateSource(), os.ErrNotExist) +} diff --git a/config/config.go b/config/config.go index 896c6e7..3535696 100644 --- a/config/config.go +++ b/config/config.go @@ -318,6 +318,8 @@ type ToolConfig struct { // If set, files created in this directory will be available for any subsequent tool calls but // will be removed when the task completes. SharedDir string `yaml:"shared-dir,omitempty"` + // BindMounts attaches existing operator-owned directories only to this container. + BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"` // Command specifies the command to execute as a list of its components. Command []string `yaml:"command,omitempty"` // Env specifies additional environment variables to set. @@ -356,6 +358,8 @@ type ServiceConfig struct { Name string `yaml:"name" validate:"required"` // Image is the Docker image used to run the service. Image string `yaml:"image" validate:"required"` + // BindMounts attaches existing operator-owned directories only to this container. + BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"` // Command overrides the image command used to start the service. Command []string `yaml:"command,omitempty"` // Env specifies static environment variables applied to every instance of the service. @@ -392,6 +396,8 @@ type ValidatorConfig struct { Name string `yaml:"name" validate:"required"` // Image is the Docker image used to run the validator. Image string `yaml:"image" validate:"required"` + // BindMounts attaches existing operator-owned directories only to this container. + BindMounts []BindMountConfig `yaml:"bind-mounts,omitempty" validate:"omitempty,dive"` // Command overrides the image command used to run validation. Each argument may use // custom-validator template variables and is passed directly to Docker without shell expansion. // Prefer TemplateFiles for values that may be large or contain arbitrary bytes, such as candidate responses. diff --git a/config/services_test.go b/config/services_test.go index 712e07b..be9ff50 100644 --- a/config/services_test.go +++ b/config/services_test.go @@ -7,6 +7,10 @@ package config import ( + "fmt" + "os" + "path" + "path/filepath" "testing" "time" @@ -176,3 +180,197 @@ func TestServiceConfigGetStartupTimeout(t *testing.T) { assert.Equal(t, DefaultServiceStartupTimeout, ServiceConfig{}.GetStartupTimeout()) assert.Equal(t, 90*time.Second, ServiceConfig{StartupTimeout: testutils.Ptr(90 * time.Second)}.GetStartupTimeout()) } + +func TestLoadConfigFromFileBindMountTargetsAndPaths(t *testing.T) { + const baseConfig = `config: + task-source: tasks.yaml + output-dir: . + providers: + - name: openai + client-config: + api-key: test-key + runs: + - name: default + model: test-model +` + loadConfig := func(t *testing.T, section string) (*Config, string, error) { + t.Helper() + configPath := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(configPath, []byte(baseConfig+section), 0o600)) + cfg, err := LoadConfigFromFile(t.Context(), configPath) + return cfg, configPath, err + } + + tests := []struct { + name string + firstTarget string + target string + sharedDir string + wantErr bool + }{ + { + name: "ancestor", + target: "/mounted", + wantErr: true, + }, + { + name: "sibling", + target: "/mounted/child", + }, + { + name: "same cleaned target", + target: "/mounted/nested/", + wantErr: true, + }, + { + name: "descendant", + target: "/mounted/nested/log", + wantErr: true, + }, + { + name: "cleaned descendant", + target: "/other/../mounted/nested/log", + wantErr: true, + }, + { + name: "root target", + target: "/", + wantErr: true, + }, + { + name: "relative target", + target: "relative", + wantErr: true, + }, + { + name: "shared directory", + target: "/shared/log", + wantErr: true, + }, + { + name: "parameter file", + target: "/param", + wantErr: true, + }, + { + name: "auxiliary directory", + target: "/aux/file", + wantErr: true, + }, + { + name: "reserved root", + target: "/other", + sharedDir: "/", + wantErr: true, + }, + { + name: "component prefix", + firstTarget: "/exports", + target: "/exports2/file", + }, + { + name: "case sensitive paths", + firstTarget: "/exports", + target: "/EXPORTS/file", + }, + { + name: "backslash is not a separator", + firstTarget: "/exports", + target: `/exports\file`, + }, + { + name: "Windows reserved name is a child", + firstTarget: "/exports", + target: "/exports/CON", + wantErr: true, + }, + { + name: "colon in a POSIX child", + firstTarget: "/exports", + target: "/exports/name:part", + wantErr: true, + }, + { + name: "cleaned unrelated target", + firstTarget: "/exports", + target: "/exports/../outside", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + firstTarget := tt.firstTarget + if firstTarget == "" { + firstTarget = "/mounted/nested" + } + sharedDir := tt.sharedDir + if sharedDir == "" { + sharedDir = "/shared" + } + section := fmt.Sprintf(` tools: + - name: tool + image: tool:test + description: Test tool + parameters: {type: object} + shared-dir: %q + auxiliary-dir: /aux + parameter-files: {p: /param} + bind-mounts: + - source: one + target: %q + - source: two + target: %q +`, sharedDir, firstTarget, tt.target) + cfg, configPath, err := loadConfig(t, section) + if tt.wantErr { + require.ErrorIs(t, err, ErrInvalidConfigProperty) + return + } + + require.NoError(t, err) + require.Len(t, cfg.Config.Tools, 1) + mounts := cfg.Config.Tools[0].BindMounts + require.Len(t, mounts, 2) + assert.Equal(t, filepath.Join(filepath.Dir(configPath), "one"), mounts[0].Source) + assert.Equal(t, filepath.Join(filepath.Dir(configPath), "two"), mounts[1].Source) + assert.Equal(t, path.Clean(tt.target), mounts[1].Target) + assert.NoDirExists(t, mounts[0].Source, "loading configuration must not create host directories") + }) + } + + for _, tt := range []struct { + name string + section string + }{ + { + name: "overlapping service mounts", + section: ` services: + - name: service + image: service:test + endpoint: {port: 8000} + bind-mounts: + - source: one + target: /exports + - source: two + target: /exports/child +`, + }, + { + name: "validator template file", + section: ` validators: + - name: validator + image: validator:test + template-files: + - path: /input/candidate + template: candidate + bind-mounts: + - source: one + target: /input/ +`, + }, + } { + t.Run(tt.name, func(t *testing.T) { + _, _, err := loadConfig(t, tt.section) + require.ErrorIs(t, err, ErrInvalidConfigProperty) + }) + } +} diff --git a/config/utils.go b/config/utils.go index 8ef20db..c08cc53 100644 --- a/config/utils.go +++ b/config/utils.go @@ -68,6 +68,10 @@ func LoadConfigFromFile(ctx context.Context, path string) (*Config, error) { return cfg, fmt.Errorf("invalid configuration definition: %w", err) } + if err := cfg.Config.resolveBindMounts(filepath.Dir(path)); err != nil { + return cfg, fmt.Errorf("invalid configuration definition: %w", err) + } + // Validate tool parameters schemas. for _, tool := range cfg.Config.Tools { if err := validateToolParameters(tool.Parameters); err != nil { diff --git a/config/utils_test.go b/config/utils_test.go index 0bd4f97..4a1e896 100644 --- a/config/utils_test.go +++ b/config/utils_test.go @@ -249,6 +249,9 @@ func TestLoadConfigFromFileServicesAndValidators(t *testing.T) { model: gpt-4 services: - name: nexus + bind-mounts: + - source: ./exports + target: /export image: nexus:test command: [nexus, service] endpoint: @@ -263,6 +266,10 @@ func TestLoadConfigFromFileServicesAndValidators(t *testing.T) { description: NEXUS client parameters: type: object + bind-mounts: + - source: ./tool-data + target: /tool-data + writable: true dependencies: - service: nexus env: @@ -271,6 +278,9 @@ func TestLoadConfigFromFileServicesAndValidators(t *testing.T) { - name: nexus image: nexus:test command: [nexus, mindtrial-validate] + bind-mounts: + - source: ./validator-data + target: /validator-data dependencies: - service: nexus env: @@ -280,6 +290,7 @@ func TestLoadConfigFromFileServicesAndValidators(t *testing.T) { cfg, err := LoadConfigFromFile(context.Background(), path) require.NoError(t, err) require.Len(t, cfg.Config.Services, 1) + require.Len(t, cfg.Config.Tools, 1) require.Len(t, cfg.Config.Validators, 1) require.NotNil(t, cfg.Config.Services[0].Endpoint) assert.Equal(t, 8000, cfg.Config.Services[0].Endpoint.Port) @@ -288,7 +299,20 @@ func TestLoadConfigFromFileServicesAndValidators(t *testing.T) { assert.Equal(t, 768, *cfg.Config.Services[0].MaxMemoryMB) require.NotNil(t, cfg.Config.Services[0].CpuPercent) assert.Equal(t, 30, *cfg.Config.Services[0].CpuPercent) + require.Len(t, cfg.Config.Tools[0].Dependencies, 1) assert.Equal(t, "{{ .Endpoint }}", cfg.Config.Tools[0].Dependencies[0].Env["NEXUS_URL"]) + require.Len(t, cfg.Config.Services[0].BindMounts, 1) + assert.Equal(t, filepath.Join(filepath.Dir(path), "exports"), cfg.Config.Services[0].BindMounts[0].Source) + assert.Equal(t, "/export", cfg.Config.Services[0].BindMounts[0].Target) + assert.False(t, cfg.Config.Services[0].BindMounts[0].Writable) + require.Len(t, cfg.Config.Tools[0].BindMounts, 1) + assert.Equal(t, filepath.Join(filepath.Dir(path), "tool-data"), cfg.Config.Tools[0].BindMounts[0].Source) + assert.Equal(t, "/tool-data", cfg.Config.Tools[0].BindMounts[0].Target) + assert.True(t, cfg.Config.Tools[0].BindMounts[0].Writable) + require.Len(t, cfg.Config.Validators[0].BindMounts, 1) + assert.Equal(t, filepath.Join(filepath.Dir(path), "validator-data"), cfg.Config.Validators[0].BindMounts[0].Source) + assert.Equal(t, "/validator-data", cfg.Config.Validators[0].BindMounts[0].Target) + assert.False(t, cfg.Config.Validators[0].BindMounts[0].Writable) } func TestLoadConfigFromFile(t *testing.T) { diff --git a/pkg/testutils/docker.go b/pkg/testutils/docker.go index e916482..31fead3 100644 --- a/pkg/testutils/docker.go +++ b/pkg/testutils/docker.go @@ -43,8 +43,10 @@ type DockerFakeContainer struct { Mounts map[string]DockerFakeMount } -// DockerFakeMount is a file bind mounted into a DockerFake container. +// DockerFakeMount describes a file or directory bound into a DockerFake container. type DockerFakeMount struct { + // DirectorySource is set only for directory mounts; temporary file sources are not stable. + DirectorySource string // Content is the mounted file content at container creation. Content []byte // ReadOnly reports whether the mount is read-only. @@ -142,12 +144,20 @@ func (f *DockerFake) create(w http.ResponseWriter, r *http.Request) { Mounts: make(map[string]DockerFakeMount, len(request.HostConfig.Mounts)), } for _, mount := range request.HostConfig.Mounts { - content, err := os.ReadFile(mount.Source) + info, err := os.Stat(mount.Source) + var content []byte + if err == nil && !info.IsDir() { + content, err = os.ReadFile(mount.Source) + } if err != nil { writeDockerJSON(w, http.StatusBadRequest, map[string]string{"message": err.Error()}) return } - created.Mounts[mount.Target] = DockerFakeMount{Content: content, ReadOnly: mount.ReadOnly} + captured := DockerFakeMount{Content: content, ReadOnly: mount.ReadOnly} + if info.IsDir() { + captured.DirectorySource = mount.Source + } + created.Mounts[mount.Target] = captured } f.mu.Lock() diff --git a/providers/tools/bind_mounts.go b/providers/tools/bind_mounts.go new file mode 100644 index 0000000..e0d4c97 --- /dev/null +++ b/providers/tools/bind_mounts.go @@ -0,0 +1,29 @@ +// Copyright (C) 2026 Petr Malik +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +package tools + +import ( + "github.com/docker/docker/api/types/mount" + "github.com/petmal/mindtrial/config" +) + +// directoryBindMounts only borrows the source. It must not create, chmod or remove it. +func directoryBindMounts(configs []config.BindMountConfig) ([]mount.Mount, error) { + var mounts []mount.Mount + for _, mountConfig := range configs { + if err := mountConfig.ValidateSource(); err != nil { + return nil, err + } + mounts = append(mounts, mount.Mount{ + Type: mount.TypeBind, + Source: mountConfig.Source, + Target: mountConfig.Target, + ReadOnly: !mountConfig.Writable, + }) + } + return mounts, nil +} diff --git a/providers/tools/bind_mounts_test.go b/providers/tools/bind_mounts_test.go new file mode 100644 index 0000000..21eeab8 --- /dev/null +++ b/providers/tools/bind_mounts_test.go @@ -0,0 +1,180 @@ +// Copyright (C) 2026 Petr Malik +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +package tools + +import ( + "encoding/json" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/petmal/mindtrial/config" + "github.com/petmal/mindtrial/pkg/testutils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestBindDirectoryRejectsMissingSourceOrFile(t *testing.T) { + missing := filepath.Join(t.TempDir(), "missing") + file := testutils.CreateMockFile(t, "bind-source-*.txt", []byte("keep")) + t.Cleanup(func() { assert.NoError(t, os.Remove(file)) }) + + tests := []struct { + name string + source string + wantErr error + }{ + { + name: "missing directory", + source: missing, + wantErr: os.ErrNotExist, + }, + { + name: "file", + source: file, + wantErr: config.ErrInvalidConfigProperty, + }, + { + name: "relative source", + source: filepath.Join("relative", "source"), + wantErr: config.ErrInvalidConfigProperty, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + docker := newServiceDocker(t, testAPIVersion) + services := testServices() + services[0].BindMounts = []config.BindMountConfig{ + { + Source: tt.source, + Target: "/exports", + Writable: true, + }, + } + taskRuntime, err := NewTaskRuntime(t.Context(), testutils.NewTestLogger(t), TaskRuntimeConfig{ + Services: services, + RequiredServices: []string{"world"}, + }) + + require.ErrorIs(t, err, ErrTaskRuntimeConfig) + require.ErrorIs(t, err, tt.wantErr) + assert.Contains(t, err.Error(), strconv.Quote(tt.source)) + assert.Nil(t, taskRuntime) + assert.Empty(t, docker.snapshot().createdNetworkIDs) + assert.Empty(t, docker.snapshot().createdIDs) + }) + } + assert.NoFileExists(t, missing) + assert.NoDirExists(t, missing) + contents, err := os.ReadFile(file) + require.NoError(t, err) + assert.Equal(t, "keep", string(contents)) +} + +func TestDockerToolExecutorBindMounts(t *testing.T) { + tests := []struct { + name string + writable bool + }{ + { + name: "read only by default", + }, + { + name: "writable", + writable: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + source := t.TempDir() + marker := filepath.Join(source, "keep.txt") + require.NoError(t, os.WriteFile(marker, []byte("keep"), 0o600)) + docker := testutils.NewDockerFake(t, testutils.DockerFakeResult{Stdout: `{"ok":true}`}) + executor, err := NewDockerToolExecutor(t.Context()) + require.NoError(t, err) + t.Cleanup(func() { + assert.NoError(t, executor.Close()) + assert.FileExists(t, marker) + }) + + toolConfig := config.ToolConfig{ + Name: "export", + Image: "tool:test", + BindMounts: []config.BindMountConfig{ + { + Source: source, + Target: "/exports", + Writable: tt.writable, + }, + }, + } + executor.RegisterTool(NewDockerTool(&toolConfig, nil, nil, nil, nil)) + result, err := executor.ExecuteTool(t.Context(), testutils.NewTestLogger(t), toolConfig.Name, json.RawMessage(`{}`), nil, nil) + require.NoError(t, err) + assert.JSONEq(t, `{"ok":true}`, string(result)) + + containers := docker.Containers() + require.Len(t, containers, 1) + require.Len(t, containers[0].Mounts, 1) + mounted, ok := containers[0].Mounts["/exports"] + require.True(t, ok) + assert.Equal(t, source, mounted.DirectorySource) + assert.Equal(t, !tt.writable, mounted.ReadOnly) + contents, err := os.ReadFile(marker) + require.NoError(t, err) + assert.Equal(t, "keep", string(contents)) + }) + } +} + +// The CI smoke uses a preloaded BusyBox image and a real daemon. No model or +// provider credentials are involved. It can be run locally with the same env var. +func TestDockerServiceFlushesBindMount(t *testing.T) { + image := os.Getenv("MINDTRIAL_TEST_BUSYBOX_IMAGE") + if image == "" { + t.Skip("set MINDTRIAL_TEST_BUSYBOX_IMAGE to a locally available BusyBox image") + } + root := t.TempDir() + service := config.ServiceConfig{ + Name: "writer", + Image: image, + Endpoint: &config.ServiceEndpointConfig{ + Port: 8000, + }, + BindMounts: []config.BindMountConfig{ + { + Source: root, + Target: "/exports", + Writable: true, + }, + }, + InputEnv: map[string]string{"output": "OUT"}, + Command: []string{"sh", "-ec", `trap 'printf closed > "$OUT.closed"; exit 0' TERM; touch "$OUT.ready"; while :; do sleep 0.1; done`}, + Healthcheck: []string{"sh", "-c", `test -f "$OUT.ready"`}, + } + cfg := TaskRuntimeConfig{ + Services: []config.ServiceConfig{service}, + RequiredServices: []string{"writer"}, + ServiceInputs: map[string]map[string]interface{}{ + "writer": {"output": "/exports/{{ .Service.InstanceID }}"}, + }, + } + for range 2 { + taskRuntime, err := NewTaskRuntime(t.Context(), testutils.NewTestLogger(t), cfg) + require.NoError(t, err) + require.NoError(t, taskRuntime.Close(t.Context())) + } + files, err := filepath.Glob(filepath.Join(root, "*.closed")) + require.NoError(t, err) + require.Len(t, files, 2) + for _, file := range files { + contents, err := os.ReadFile(file) + require.NoError(t, err) + assert.Equal(t, "closed", string(contents)) + } +} diff --git a/providers/tools/docker_executor.go b/providers/tools/docker_executor.go index 1f4ea80..b0e0498 100644 --- a/providers/tools/docker_executor.go +++ b/providers/tools/docker_executor.go @@ -388,8 +388,13 @@ func (d *DockerToolExecutor) executeDockerTool(ctx context.Context, logger loggi defer os.RemoveAll(tempDir) // clean up temp directory after execution logger.Message(ctx, logging.LevelDebug, "created temporary workspace directory: %s", tempDir) - // Write parameter files and create individual file mounts. - var mounts []mount.Mount + // Start with operator-owned directories, then add MindTrial-managed files and scratch. + mounts, err := directoryBindMounts(tool.bindMounts) + if err != nil { + wrapErr := fmt.Errorf("%w: %w", ErrToolInternal, err) + summary.Status, summary.ErrorMessage = toolCallStatusInfrastructureError, wrapErr.Error() + return nil, wrapErr + } for argName, containerPath := range tool.parameterFiles { if argValue, exists := argMap[argName]; exists { // Convert argument value to string. @@ -785,6 +790,7 @@ type DockerTool struct { parameters map[string]interface{} parameterFiles map[string]string auxiliaryDir string + bindMounts []config.BindMountConfig sharedDir string command []string env map[string]string @@ -805,6 +811,7 @@ func NewDockerTool(cfg *config.ToolConfig, maxCalls *int, timeout *time.Duration parameters: cfg.Parameters, parameterFiles: cfg.ParameterFiles, auxiliaryDir: cfg.AuxiliaryDir, + bindMounts: cfg.BindMounts, sharedDir: cfg.SharedDir, command: cfg.Command, env: cfg.Env, diff --git a/providers/tools/docker_executor_test.go b/providers/tools/docker_executor_test.go index 4623242..7f9c2ab 100644 --- a/providers/tools/docker_executor_test.go +++ b/providers/tools/docker_executor_test.go @@ -40,6 +40,7 @@ type dockerAPIMock struct { onPing func(http.ResponseWriter, *http.Request) onImageInspect func(http.ResponseWriter, *http.Request) onCreate func(http.ResponseWriter, *http.Request) + onStop func(http.ResponseWriter, *http.Request) onStart func(http.ResponseWriter, *http.Request) onWait func(http.ResponseWriter, *http.Request) onLogs func(http.ResponseWriter, *http.Request) @@ -111,6 +112,9 @@ func (m *dockerAPIMock) handle(w http.ResponseWriter, r *http.Request) { } m.onStart(w, r) return + case r.Method == http.MethodPost && strings.HasSuffix(trimmed, "/stop") && m.onStop != nil: + m.onStop(w, r) + return case r.Method == http.MethodPost && strings.HasSuffix(trimmed, "/wait"): if m.onWait == nil { m.t.Fatalf("unexpected ContainerWait call without handler: %s", path) @@ -196,9 +200,10 @@ type containerCreatePayload struct { } `json:"Healthcheck"` HostConfig struct { Mounts []struct { - Type string `json:"Type"` - Source string `json:"Source"` - Target string `json:"Target"` + Type string `json:"Type"` + Source string `json:"Source"` + Target string `json:"Target"` + ReadOnly bool `json:"ReadOnly"` } `json:"Mounts"` AutoRemove bool `json:"AutoRemove"` NetworkMode string `json:"NetworkMode"` diff --git a/providers/tools/docker_helpers.go b/providers/tools/docker_helpers.go index 13483df..5636d03 100644 --- a/providers/tools/docker_helpers.go +++ b/providers/tools/docker_helpers.go @@ -29,6 +29,19 @@ func dockerResourceName(kind string) string { return "mindtrial-" + kind + "-" + strings.ToLower(ulid.Make().String()) } +// stopDockerService gives an initialized service a bounded grace period, even when +// the evaluation was cancelled. Close still attempts forced removal on any error. +func stopDockerService(ctx context.Context, cli *client.Client, id string) error { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerCleanupTimeout) + defer cancel() + seconds := 10 + err := cli.ContainerStop(cleanupCtx, id, container.StopOptions{Timeout: &seconds}) + if errdefs.IsNotFound(err) { + return nil + } + return err +} + func removeDockerContainer(ctx context.Context, cli *client.Client, containerID string) error { cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dockerCleanupTimeout) defer cancel() diff --git a/providers/tools/task_runtime.go b/providers/tools/task_runtime.go index b296a5d..560f4b3 100644 --- a/providers/tools/task_runtime.go +++ b/providers/tools/task_runtime.go @@ -91,7 +91,8 @@ type TaskRuntimeConfig struct { RequiredServices []string // ServiceInputs supplies task inputs keyed by service name and input name. ServiceInputs map[string]map[string]interface{} - // TemplateData is exposed to string service-input templates. + // TemplateData supplies execution metadata to string service-input templates. + // Each template also receives Service.InstanceID, the generated container name. TemplateData ExecutionTemplateData } @@ -209,7 +210,12 @@ func (r *TaskRuntime) startService(ctx context.Context, logger logging.Logger, s serviceLogger := logger.WithContext(fmt.Sprintf("service %s: ", service.Name)) serviceLogger.Message(ctx, logging.LevelInfo, "starting setup") - env, err := r.resolveServiceEnv(service) + mounts, err := directoryBindMounts(service.BindMounts) + if err != nil { + return fmt.Errorf("%w: service %q: %w", ErrTaskRuntimeConfig, service.Name, err) + } + containerName := dockerResourceName("service") + env, err := r.resolveServiceEnv(service, containerName) if err != nil { return err } @@ -255,6 +261,7 @@ func (r *TaskRuntime) startService(ctx context.Context, logger logging.Logger, s } } hostConfig := &container.HostConfig{ + Mounts: mounts, NetworkMode: container.NetworkMode(instance.networkName), RestartPolicy: container.RestartPolicy{Name: container.RestartPolicyDisabled}, LogConfig: container.LogConfig{Type: "json-file"}, @@ -270,7 +277,6 @@ func (r *TaskRuntime) startService(ctx context.Context, logger logging.Logger, s instance.networkName: {Aliases: []string{instance.Host}}, }} - containerName := dockerResourceName("service") created, err := r.client.ContainerCreate(ctx, containerConfig, hostConfig, networkingConfig, nil, containerName) if err != nil { return fmt.Errorf("%w: failed to create service %q container: %w", ErrTaskRuntimeInternal, service.Name, err) @@ -331,14 +337,20 @@ func ociImageLabels(labels map[string]string) []string { return result } -func (r *TaskRuntime) resolveServiceEnv(service config.ServiceConfig) (map[string]string, error) { +func (r *TaskRuntime) resolveServiceEnv(service config.ServiceConfig, containerName string) (map[string]string, error) { + data := serviceInputTemplateData{ + ExecutionTemplateData: r.templateData, + Service: serviceInputTemplateService{ + InstanceID: containerName, + }, + } env := make(map[string]string, len(service.Env)+len(r.serviceInputs[service.Name])) for name, value := range service.Env { env[name] = value } for inputName, rawValue := range r.serviceInputs[service.Name] { envName := service.InputEnv[inputName] - value, err := resolveServiceInput(rawValue, r.templateData) + value, err := resolveServiceInput(rawValue, data) if err != nil { return nil, fmt.Errorf("%w: service %q input %q: %w", ErrTaskRuntimeConfig, service.Name, inputName, err) } @@ -350,7 +362,17 @@ func (r *TaskRuntime) resolveServiceEnv(service config.ServiceConfig) (map[strin return env, nil } -func resolveServiceInput(value interface{}, data ExecutionTemplateData) (string, error) { +// serviceInputTemplateData adds the new service instance to the execution metadata. +type serviceInputTemplateData struct { + ExecutionTemplateData + Service serviceInputTemplateService +} + +type serviceInputTemplateService struct { + InstanceID string +} + +func resolveServiceInput(value interface{}, data serviceInputTemplateData) (string, error) { raw, ok := value.(string) if !ok { return fmt.Sprint(value), nil @@ -512,8 +534,14 @@ func (r *TaskRuntime) Close(ctx context.Context) error { var errs []error serviceNames := utils.SortedKeys(r.instances) for _, name := range serviceNames { - r.logServiceDiagnostics(ctx, r.logger.WithContext(fmt.Sprintf("service %s: ", name)), logging.LevelTrace, r.instances[name].containerID) - if err := removeDockerContainer(ctx, r.client, r.instances[name].containerID); err != nil { + id := r.instances[name].containerID + // Stop before collecting logs and removing the container: services may flush + // their files and report final diagnostics when they receive the stop signal. + if err := stopDockerService(ctx, r.client, id); err != nil { + errs = append(errs, fmt.Errorf("%w: stop service %q: %w", ErrTaskRuntimeInternal, name, err)) + } + r.logServiceDiagnostics(ctx, r.logger.WithContext(fmt.Sprintf("service %s: ", name)), logging.LevelTrace, id) + if err := removeDockerContainer(ctx, r.client, id); err != nil { errs = append(errs, fmt.Errorf("%w: remove service %q container: %w", ErrTaskRuntimeInternal, name, err)) } } diff --git a/providers/tools/task_runtime_test.go b/providers/tools/task_runtime_test.go index 71f4a8a..153cf05 100644 --- a/providers/tools/task_runtime_test.go +++ b/providers/tools/task_runtime_test.go @@ -34,6 +34,7 @@ type serviceDocker struct { mu sync.Mutex state serviceDockerState stopped map[string]bool + failStop bool stopAll bool healthSequence []string failImage string @@ -152,6 +153,20 @@ func newServiceDocker(t *testing.T, apiVersion string) *serviceDocker { } writeJSON(t, w, http.StatusOK, inspected) } + mock.onStop = func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, mock.basePath()+"/containers/"), "/stop") + assert.Equal(t, "10", r.URL.Query().Get("t")) + docker.mu.Lock() + assert.NotContains(t, docker.state.removedContainers, id) + docker.stopped[id] = true + fail := docker.failStop + docker.mu.Unlock() + if fail { + writeJSON(t, w, http.StatusInternalServerError, map[string]string{"message": "stop failed"}) + return + } + w.WriteHeader(http.StatusNoContent) + } mock.onWait = func(w http.ResponseWriter, _ *http.Request) { writeJSON(t, w, http.StatusOK, map[string]int{"StatusCode": 0}) } @@ -737,19 +752,41 @@ func TestIsTaskRuntimeError(t *testing.T) { } func TestTaskRuntimeServiceInputTemplateErrors(t *testing.T) { - newServiceDocker(t, testAPIVersion) - - _, err := NewTaskRuntime(t.Context(), testutils.NewTestLogger(t), TaskRuntimeConfig{ - Services: testServices(), - RequiredServices: []string{"world"}, - ServiceInputs: map[string]map[string]interface{}{ - "world": {"seed": "{{ .Evaluation.Missing }}"}, + tests := []struct { + name string + template string + }{ + { + name: "unknown evaluation field", + template: "{{ .Evaluation.Missing }}", }, - TemplateData: testTemplateData(), - }) + { + name: "unknown service field", + template: "{{ .Service.Missing }}", + }, + { + name: "old unscoped instance field", + template: "{{ .ServiceInstance }}", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + docker := newServiceDocker(t, testAPIVersion) - require.ErrorIs(t, err, ErrTaskRuntimeConfig) - assert.Contains(t, err.Error(), `service "world" input "seed"`) + _, err := NewTaskRuntime(t.Context(), testutils.NewTestLogger(t), TaskRuntimeConfig{ + Services: testServices(), + RequiredServices: []string{"world"}, + ServiceInputs: map[string]map[string]interface{}{ + "world": {"seed": tt.template}, + }, + TemplateData: testTemplateData(), + }) + + require.ErrorIs(t, err, ErrTaskRuntimeConfig) + assert.Contains(t, err.Error(), `service "world" input "seed"`) + assert.Empty(t, docker.snapshot().createdNetworkIDs) + }) + } } func TestNewTaskRuntimeLogsServiceImageIdentity(t *testing.T) { @@ -905,3 +942,62 @@ func (l *recordingLogger) find(substring string) (recordedLogMessage, bool) { } return recordedLogMessage{}, false } + +func TestServiceBindDirectoryIsPrivateAndNewInstancePerRetry(t *testing.T) { + docker := newServiceDocker(t, testAPIVersion) + source := t.TempDir() + services := testServices() + services[0].BindMounts = []config.BindMountConfig{ + { + Source: source, + Target: "/exports", + Writable: true, + }, + } + cfg := TaskRuntimeConfig{ + Services: services, + RequiredServices: []string{"world", "shop"}, + TemplateData: testTemplateData(), + ServiceInputs: map[string]map[string]interface{}{ + "world": {"seed": "/exports/{{ .Service.InstanceID }}/{{ .Evaluation.Seed }}/{{ .Task.Name }}/{{ .Provider.Name }}/{{ .Run.Name }}"}, + }, + } + usedNames := map[string]bool{} + for range 2 { + createdCount := len(docker.snapshot().createdIDs) + taskRuntime, err := NewTaskRuntime(t.Context(), testutils.NewTestLogger(t), cfg) + require.NoError(t, err) + snapshot := docker.snapshot() + require.Len(t, snapshot.createdIDs, createdCount+2) + containerID := snapshot.createdIDs[createdCount] + shopContainerID := snapshot.createdIDs[createdCount+1] + assert.Equal(t, "world:latest", snapshot.containers[containerID].Image) + assert.Equal(t, "shop:latest", snapshot.containers[shopContainerID].Image) + containerName := snapshot.containerNames[containerID] + require.NotEmpty(t, containerName) + assert.False(t, usedNames[containerName]) + usedNames[containerName] = true + assert.Contains(t, snapshot.containers[containerID].Env, "WORLD_SEED=/exports/"+containerName+"/eval-seed/task-a/provider-a/run-a") + mounts := snapshot.containers[containerID].HostConfig.Mounts + require.Len(t, mounts, 1) + assert.Equal(t, "bind", mounts[0].Type) + assert.Equal(t, source, mounts[0].Source) + assert.Equal(t, "/exports", mounts[0].Target) + assert.False(t, mounts[0].ReadOnly) + assert.Empty(t, snapshot.containers[shopContainerID].HostConfig.Mounts) + require.NoError(t, taskRuntime.Close(t.Context())) + docker.configure(func() { assert.True(t, docker.stopped[containerID]) }) + assert.DirExists(t, source) + } +} + +func TestServiceStopFailureStillRemovesResources(t *testing.T) { + docker := newServiceDocker(t, testAPIVersion) + taskRuntime := newTestTaskRuntime(t, "shop") + docker.configure(func() { docker.failStop = true }) + err := taskRuntime.Close(t.Context()) + require.ErrorIs(t, err, ErrTaskRuntimeInternal) + state := docker.snapshot() + assert.Equal(t, state.createdIDs, state.removedContainers) + assert.Equal(t, state.createdNetworkIDs, state.removedNetworks) +} diff --git a/runners/bind_mounts_test.go b/runners/bind_mounts_test.go new file mode 100644 index 0000000..58d2bc7 --- /dev/null +++ b/runners/bind_mounts_test.go @@ -0,0 +1,137 @@ +// Copyright (C) 2026 Petr Malik +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +package runners + +import ( + "context" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/petmal/mindtrial/config" + "github.com/petmal/mindtrial/pkg/testutils" + "github.com/petmal/mindtrial/validators" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRunnerPreflightBindMountSources(t *testing.T) { + entryPoints := []struct { + name string + run func(*defaultRunner, context.Context, []config.Task) (ResultSet, error) + }{ + { + name: "Run", + run: (*defaultRunner).Run, + }, + { + name: "Start", + run: func(runner *defaultRunner, ctx context.Context, tasks []config.Task) (ResultSet, error) { + return runner.Start(ctx, tasks) + }, + }, + } + for _, entry := range entryPoints { + for _, consumer := range []string{"tool", "service via tool", "custom validator", "service via validator"} { + for _, sourceKind := range []string{"directory", "missing", "file", "relative", "unused"} { + if entry.name == "Start" && (sourceKind == "directory" || sourceKind == "unused") { + continue + } + t.Run(entry.name+"/"+consumer+"/"+sourceKind, func(t *testing.T) { + source := t.TempDir() + var wantErr error + switch sourceKind { + case "missing", "unused": + source = filepath.Join(source, "missing") + wantErr = os.ErrNotExist + case "file": + source = testutils.CreateMockFile(t, "bind-source-*.txt", []byte("keep")) + t.Cleanup(func() { assert.NoError(t, os.Remove(source)) }) + wantErr = config.ErrInvalidConfigProperty + case "relative": + source = "relative-source" + wantErr = config.ErrInvalidConfigProperty + } + mounts := []config.BindMountConfig{ + { + Source: source, + Target: "/exports", + }, + } + tools := taskServicesTestTools() + services := taskServicesTestServices() + validator := worldStateValidator() + validator.Dependencies = nil + var task config.Task + var wantConsumer string + switch consumer { + case "tool": + tools[1].BindMounts = mounts + task = newToolTask(t, "python") + wantConsumer = "tool 'python'" + case "service via tool": + services[0].BindMounts = mounts + task = newToolTask(t, "world-client") + wantConsumer = "service 'world'" + case "custom validator": + validator.BindMounts = mounts + task = newCustomValidatedTask(t, "task", validator.Name, nil) + wantConsumer = "custom validator 'world-state'" + case "service via validator": + services[0].BindMounts = mounts + validator.Dependencies = []config.ServiceDependency{ + { + Service: "world", + }, + } + task = newCustomValidatedTask(t, "task", validator.Name, nil) + wantConsumer = "service 'world'" + } + if sourceKind == "unused" { + task = newTaskServicesTask(t, "unused", config.ToolSelector{ + ServiceInputs: map[string]map[string]interface{}{ + "world": {"seed": "unused"}, + }, + }, &config.ToolSelector{ + Disabled: testutils.Ptr(true), + Tools: []config.ToolSelection{{Name: "world-client"}, {Name: "python"}}, + }) + wantErr = nil + } + customValidators := []config.ValidatorConfig{validator} + runner := &defaultRunner{ + validatorFactory: validators.NewFactoryWithCustomValidators(nil, customValidators), + tools: tools, + taskRuntime: taskRuntimeConfig{ + services: services, + customValidators: customValidators, + }, + logger: zerolog.Nop(), + toolValidator: &stubToolValidator{}, + } + // A later invalid task must block the whole batch, not just that task. + tasks := []config.Task{newToolTask(t), task, task} + results, err := entry.run(runner, t.Context(), tasks) + if wantErr != nil { + require.ErrorIs(t, err, wantErr) + require.ErrorIs(t, err, config.ErrInvalidConfigProperty) + assert.Nil(t, results, "preflight failure must not start task execution") + assert.Contains(t, err.Error(), wantConsumer+" cannot be used") + assert.Equal(t, 1, strings.Count(err.Error(), strconv.Quote(source)), "each selected definition is checked once") + return + } + require.NoError(t, err) + require.NotNil(t, results) + assert.Empty(t, results.GetResults()) + }) + } + } + } +} diff --git a/runners/default_runner.go b/runners/default_runner.go index c9d0e81..55a4012 100644 --- a/runners/default_runner.go +++ b/runners/default_runner.go @@ -237,6 +237,7 @@ func (r *defaultRunner) assertCanRun(ctx context.Context, tasks []config.Task) e taskErrors = append(taskErrors, fmt.Errorf("task '%s' requires custom validator '%s': %w", task.Name, validatorName, err)) } else if validatorConfig, ok := r.customValidatorConfig(validatorName); ok { if !validatedValidators[validatorName] { + taskErrors = append(taskErrors, validateBindMountSources(fmt.Sprintf("custom validator '%s'", validatorName), validatorConfig.BindMounts)...) if err := r.toolValidator.ValidateImage(ctx, validatorConfig.Image); err != nil { taskErrors = append(taskErrors, fmt.Errorf("custom validator '%s' cannot be used: %w", validatorName, err)) } @@ -261,6 +262,7 @@ func (r *defaultRunner) assertCanRun(ctx context.Context, tasks []config.Task) e } if _, alreadyValidated := validatedTools[toolName]; !alreadyValidated { + taskErrors = append(taskErrors, validateBindMountSources(fmt.Sprintf("tool '%s'", toolName), toolCfg.BindMounts)...) if err := r.toolValidator.ValidateTool(ctx, toolCfg); err != nil { taskErrors = append(taskErrors, fmt.Errorf("tool '%s' cannot be used: %w", toolName, err)) } @@ -310,7 +312,7 @@ func (r *defaultRunner) assertCanRun(ctx context.Context, tasks []config.Task) e } // validateServiceDependencies checks that every dependency of consumer names an available service -// with a usable image and compilable environment templates. +// with a usable image, existing bind sources, and compilable environment templates. func (r *defaultRunner) validateServiceDependencies(ctx context.Context, consumer string, dependencies []config.ServiceDependency, availableServices map[string]config.ServiceConfig, validatedServices map[string]bool) (errs []error) { for _, dependency := range dependencies { serviceCfg, exists := availableServices[dependency.Service] @@ -319,6 +321,7 @@ func (r *defaultRunner) validateServiceDependencies(ctx context.Context, consume continue } if !validatedServices[dependency.Service] { + errs = append(errs, validateBindMountSources(fmt.Sprintf("service '%s'", dependency.Service), serviceCfg.BindMounts)...) if err := r.toolValidator.ValidateImage(ctx, serviceCfg.Image); err != nil { errs = append(errs, fmt.Errorf("service '%s' cannot be used: %w", dependency.Service, err)) } @@ -333,6 +336,15 @@ func (r *defaultRunner) validateServiceDependencies(ctx context.Context, consume return errs } +func validateBindMountSources(consumer string, mounts []config.BindMountConfig) (errs []error) { + for _, mount := range mounts { + if err := mount.ValidateSource(); err != nil { + errs = append(errs, fmt.Errorf("%s cannot be used: %w", consumer, err)) + } + } + return errs +} + func (r *defaultRunner) Start(ctx context.Context, tasks []config.Task) (AsyncResultSet, error) { if err := r.assertCanRun(ctx, tasks); err != nil { return nil, err diff --git a/validators/custom_validator.go b/validators/custom_validator.go index 6147c95..90e4217 100644 --- a/validators/custom_validator.go +++ b/validators/custom_validator.go @@ -139,6 +139,7 @@ func (v *customValidator) IsCorrectWithEnvironment( Image: v.config.Image, Description: "MindTrial trusted custom validator.", Parameters: map[string]interface{}{"type": "object"}, + BindMounts: v.config.BindMounts, Command: command, Env: env, Dependencies: v.config.Dependencies, diff --git a/validators/custom_validator_test.go b/validators/custom_validator_test.go index 50e6a5c..80b6a6a 100644 --- a/validators/custom_validator_test.go +++ b/validators/custom_validator_test.go @@ -228,9 +228,16 @@ func TestCustomValidatorTemplateFilesCarryArbitraryCandidates(t *testing.T) { docker := testutils.NewDockerFake(t, testutils.DockerFakeResult{Stdout: validCustomValidatorResponse}) candidate := strings.Repeat("x", 256*1024) + "\x00-tail" + source := t.TempDir() _, err := validateWithCustomValidator(t, config.ValidatorConfig{ - Name: "world-state", - Image: "validator:test", + Name: "world-state", + Image: "validator:test", + BindMounts: []config.BindMountConfig{ + { + Source: source, + Target: "/fixtures", + }, + }, Command: []string{"validate", "--candidate-file", "/input/candidate", "--task={{ .Task.Name }}"}, TemplateFiles: []config.ValidatorTemplateFile{ {Path: "/input/candidate", Template: "{{ .Candidate.Response }}"}, @@ -244,6 +251,8 @@ func TestCustomValidatorTemplateFilesCarryArbitraryCandidates(t *testing.T) { assert.Equal(t, []string{"validate", "--candidate-file", "/input/candidate", "--task=world-task"}, containers[0].Cmd) assert.Equal(t, []byte(candidate), containers[0].Mounts["/input/candidate"].Content, "file content must be exact bytes") assert.JSONEq(t, `"`+strings.Repeat("x", 256*1024)+`\u0000-tail"`, string(containers[0].Mounts["/input/candidate.json"].Content)) + assert.Equal(t, source, containers[0].Mounts["/fixtures"].DirectorySource) + assert.True(t, containers[0].Mounts["/fixtures"].ReadOnly) } func TestCustomValidatorTemplateRenderingErrors(t *testing.T) {