-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix: isolate detached command context from parent cancellation #179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mason5052
wants to merge
3
commits into
vxcontrol:master
Choose a base branch
from
mason5052:fix/detached-cmd-context-isolation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| package tools | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "context" | ||
| "io" | ||
| "net" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "pentagi/pkg/database" | ||
| "pentagi/pkg/docker" | ||
|
|
||
| "github.com/docker/docker/api/types" | ||
| "github.com/docker/docker/api/types/container" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| // contextTestTermLogProvider implements TermLogProvider for context tests. | ||
| type contextTestTermLogProvider struct{} | ||
|
|
||
| func (m *contextTestTermLogProvider) PutMsg(_ context.Context, _ database.TermlogType, _ string, | ||
| _ int64, _, _ *int64) (int64, error) { | ||
| return 1, nil | ||
| } | ||
|
|
||
| var _ TermLogProvider = (*contextTestTermLogProvider)(nil) | ||
|
|
||
| // contextAwareMockDockerClient tracks whether the context was canceled | ||
| // when getExecResult runs, proving context.WithoutCancel works. | ||
| type contextAwareMockDockerClient struct { | ||
| isRunning bool | ||
| execCreateResp container.ExecCreateResponse | ||
| attachOutput []byte | ||
| attachDelay time.Duration | ||
| inspectResp container.ExecInspect | ||
|
|
||
| // Set by ContainerExecAttach to track if ctx was canceled during attach | ||
| ctxWasCanceled bool | ||
| } | ||
|
|
||
| func (m *contextAwareMockDockerClient) SpawnContainer(_ context.Context, _ string, _ database.ContainerType, | ||
| _ int64, _ *container.Config, _ *container.HostConfig) (database.Container, error) { | ||
| return database.Container{}, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) StopContainer(_ context.Context, _ string, _ int64) error { | ||
| return nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) DeleteContainer(_ context.Context, _ string, _ int64) error { | ||
| return nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) IsContainerRunning(_ context.Context, _ string) (bool, error) { | ||
| return m.isRunning, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) ContainerExecCreate(_ context.Context, _ string, _ container.ExecOptions) (container.ExecCreateResponse, error) { | ||
| return m.execCreateResp, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) ContainerExecAttach(ctx context.Context, _ string, _ container.ExecAttachOptions) (types.HijackedResponse, error) { | ||
| // Wait for the configured delay, simulating a long-running command | ||
| if m.attachDelay > 0 { | ||
| select { | ||
| case <-time.After(m.attachDelay): | ||
| // Command completed normally | ||
| case <-ctx.Done(): | ||
| // Context was canceled -- this is the bug behavior (without WithoutCancel) | ||
| m.ctxWasCanceled = true | ||
| return types.HijackedResponse{}, ctx.Err() | ||
| } | ||
| } | ||
|
|
||
| // Check if context was already canceled by the time we get here | ||
| select { | ||
| case <-ctx.Done(): | ||
| m.ctxWasCanceled = true | ||
| return types.HijackedResponse{}, ctx.Err() | ||
| default: | ||
| } | ||
|
|
||
| pr, pw := net.Pipe() | ||
| go func() { | ||
| pw.Write(m.attachOutput) | ||
| pw.Close() | ||
| }() | ||
|
|
||
| return types.HijackedResponse{ | ||
| Conn: pr, | ||
| Reader: bufio.NewReader(pr), | ||
| }, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) ContainerExecInspect(_ context.Context, _ string) (container.ExecInspect, error) { | ||
| return m.inspectResp, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) CopyToContainer(_ context.Context, _ string, _ string, _ io.Reader, _ container.CopyToContainerOptions) error { | ||
| return nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) CopyFromContainer(_ context.Context, _ string, _ string) (io.ReadCloser, container.PathStat, error) { | ||
| return io.NopCloser(nil), container.PathStat{}, nil | ||
| } | ||
| func (m *contextAwareMockDockerClient) Cleanup(_ context.Context) error { return nil } | ||
| func (m *contextAwareMockDockerClient) GetDefaultImage() string { return "test-image" } | ||
|
|
||
| var _ docker.DockerClient = (*contextAwareMockDockerClient)(nil) | ||
|
|
||
| func TestExecCommandDetachSurvivesParentCancel(t *testing.T) { | ||
| // This test validates the fix for Issue #176: | ||
| // Detached commands must NOT be killed when the parent context is canceled. | ||
| // | ||
| // Before the fix: detached goroutine used parent ctx directly, so when the | ||
| // parent was canceled (e.g., agent delegation timeout), ctx.Done() fired | ||
| // in getExecResult and killed the background command. | ||
| // | ||
| // After the fix: context.WithoutCancel(ctx) creates an isolated context | ||
| // that preserves values but ignores parent cancellation. | ||
|
|
||
| mock := &contextAwareMockDockerClient{ | ||
| isRunning: true, | ||
| execCreateResp: container.ExecCreateResponse{ID: "exec-cancel-test"}, | ||
| attachOutput: []byte("background result"), | ||
| attachDelay: 2 * time.Second, // simulates a long-running command | ||
| inspectResp: container.ExecInspect{ExitCode: 0}, | ||
| } | ||
|
|
||
| term := &terminal{ | ||
| flowID: 1, | ||
| containerID: 1, | ||
| containerLID: "test-container", | ||
| dockerClient: mock, | ||
| tlp: &contextTestTermLogProvider{}, | ||
| } | ||
|
|
||
| // Create a cancellable parent context | ||
| parentCtx, cancel := context.WithCancel(context.Background()) | ||
|
|
||
| // Start ExecCommand with detach=true (returns quickly due to quick check timeout) | ||
| output, err := term.ExecCommand(parentCtx, "/work", "long-running-scan", true, 5*time.Minute) | ||
| assert.NoError(t, err) | ||
| assert.Contains(t, output, "Command started in background") | ||
|
|
||
| // Cancel the parent context -- simulating agent delegation timeout | ||
| cancel() | ||
|
|
||
| // Wait enough time for the detached goroutine to complete its work. | ||
| // If context.WithoutCancel is working correctly, the goroutine should | ||
| // NOT see ctx.Done() and should complete normally after attachDelay. | ||
| // If the fix regresses, ctxWasCanceled will be true. | ||
| time.Sleep(3 * time.Second) | ||
|
|
||
| assert.False(t, mock.ctxWasCanceled, | ||
| "detached goroutine should NOT see parent context cancellation (context.WithoutCancel must be used)") | ||
| } | ||
|
|
||
| func TestExecCommandNonDetachRespectsParentCancel(t *testing.T) { | ||
| // Counterpart: non-detached commands SHOULD respect parent cancellation. | ||
| // This ensures we didn't accidentally apply WithoutCancel to the non-detach path. | ||
|
|
||
| mock := &contextAwareMockDockerClient{ | ||
| isRunning: true, | ||
| execCreateResp: container.ExecCreateResponse{ID: "exec-nondetach-cancel"}, | ||
| attachOutput: []byte("should not complete"), | ||
| attachDelay: 5 * time.Second, // longer than cancel delay | ||
| inspectResp: container.ExecInspect{ExitCode: 0}, | ||
| } | ||
|
|
||
| term := &terminal{ | ||
| flowID: 1, | ||
| containerID: 1, | ||
| containerLID: "test-container", | ||
| dockerClient: mock, | ||
| tlp: &contextTestTermLogProvider{}, | ||
| } | ||
|
|
||
| parentCtx, cancel := context.WithCancel(context.Background()) | ||
|
|
||
| // Cancel after 200ms -- non-detached command should see this | ||
| go func() { | ||
| time.Sleep(200 * time.Millisecond) | ||
| cancel() | ||
| }() | ||
|
|
||
| _, err := term.ExecCommand(parentCtx, "/work", "long-command", false, 5*time.Minute) | ||
|
|
||
| // Non-detached command should fail with context error | ||
| assert.Error(t, err) | ||
| assert.True(t, mock.ctxWasCanceled, | ||
| "non-detached command SHOULD see parent context cancellation") | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new detached execution behavior (using context.WithoutCancel) isn’t covered by tests. Since other tools in this package have unit tests, consider adding a terminal ExecCommand test that cancels the parent ctx and asserts the detached goroutine continues (e.g., via a mock dockerClient that would otherwise abort when ctx.Done() closes), while the command still stops on its own timeout.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Valid suggestion. However, writing a meaningful test for this requires mocking the Docker client (ContainerExecCreate, ContainerExecAttach, etc.) and verifying goroutine behavior under cancellation -- which is fairly involved and would require test infrastructure that does not exist yet in this package. For a 2-line bugfix that uses an idiomatic Go pattern (context.WithoutCancel), I think the current verification (manual code review + go vet + build) is proportionate. Happy to add tests in a follow-up PR if the maintainers prefer.