Skip to content

GitRunner can wait on filter subprocesses after cancellation #1907

Closed

Description

@enonnay

OpenCodeReview Version

Source snapshot: a6b57ecaa002c01f1f0b361866de89b318dc4a7a.

Operating System

Windows (windows/amd64, Go 1.27.3, Git 2.56.0.windows.1 at C:/Program Files/Git/cmd/git.exe). Linux and macOS have not been tested.

Installation Method

Source-level reproduction with a standalone Go harness. No installed OCR CLI was invoked.

LLM Provider

Not applicable; no model requests were made.

Bug Description

With a slow Git clean filter, cancelling a GitRunner request does not promptly return or release its concurrency slot. Under a 200ms context deadline, RunSplit took 6.505s to return and Stream took 6.169s. A second request queued behind the cancelled Stream call also timed out waiting for the semaphore slot.

The harness uses the Runner source from internal/gitcmd/runner.go at the pinned commit, with only its package declaration changed. This demonstrates the shared Runner execution behavior rather than an end-to-end OCR review failure.

In internal/gitcmd/runner.go:

  • Run, Output, RunSplit, and Stream construct commands with exec.CommandContext and leave WaitDelay unset (0). Per os/exec.Cmd, when WaitDelay is zero, I/O pipes are read until EOF, which may not occur after cancellation while a subprocess that inherited the pipe descriptors keeps them open.
  • When WaitDelay is non-zero, Go starts the delay timer when either the associated Context is done or Wait observes that the child process has exited, whichever occurs first, and closes open parent I/O pipes (including StdoutPipe) once the delay elapses.
  • In Stream (L93-L130), consume(stdoutPipe) runs before cmd.Wait() (L114-L118). With WaitDelay unset, consume blocks until the helper closes stdout; if WaitDelay closes the pipe after cancellation, consume unblocks with a closed-pipe read error (read |0: file already closed), which Stream currently returns directly (if consumeErr != nil { return consumeErr }).

In OCR, a shared GitRunner (cmd/opencodereview/shared.go) is used by callers with per-call timeouts—such as FileReader.ReadLines (Stream, 30s timeout in internal/tool/filereader.go), CodeSearchProvider.runGitGrep (RunSplit, 10s timeout in internal/tool/code_search.go), FileFindProvider.listGitFiles (Output, 10s timeout), and sniffer.showAtRef (Output, 5s timeout)—as well as diff loading during ocr review.

Steps to Reproduce

Tested environment: Windows (windows/amd64), Go 1.27.3, Git 2.56.0.windows.1 (C:/Program Files/Git/cmd/git.exe).

  1. Copy internal/gitcmd/runner.go from a6b57ecaa002c01f1f0b361866de89b318dc4a7a into a scratch module directory as runner.go, changing package gitcmd to package main.
  2. Create filter.go, runsplit_probe.go, and stream_probe.go in the same directory:

filter.go:

package main

import (
	"io"
	"os"
	"time"
)

func main() {
	time.Sleep(3 * time.Second)
	io.Copy(os.Stdout, os.Stdin)
}

runsplit_probe.go:

package main

import (
	"context"
	"fmt"
	"os"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()
	start := time.Now()
	stdout, stderr, err := New(1).RunSplit(ctx, os.Args[1], "diff", "--no-ext-diff", "--no-textconv", "HEAD", "--")
	fmt.Printf("elapsed=%s context=%v command_error=%v stdout_bytes=%d stderr_bytes=%d\n",
		time.Since(start).Round(time.Millisecond), ctx.Err(), err, len(stdout), len(stderr))
}

stream_probe.go:

package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"
)

func main() {
	runner := New(1)
	ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()
	started := time.Now()
	done := make(chan error, 1)
	go func() {
		done <- runner.Stream(ctx, os.Args[1], func(reader io.Reader) error {
			_, err := io.Copy(io.Discard, reader)
			return err
		}, "diff", "--no-ext-diff", "--no-textconv", "HEAD", "--")
	}()
	<-ctx.Done()
	queuedCtx, queuedCancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer queuedCancel()
	_, queuedErr := runner.Run(queuedCtx, os.Args[1], "status", "--porcelain")
	fmt.Printf("context=%v semaphore_slots_held=%d queued_request=%v\n", ctx.Err(), len(runner.sem), queuedErr)
	select {
	case err := <-done:
		fmt.Printf("stream_elapsed=%s stream_error=%v\n", time.Since(started).Round(time.Millisecond), err)
	case <-time.After(12 * time.Second):
		fmt.Println("stream_probe_still_waiting_after_12_seconds")
	}
}
  1. Build the filter helper, initialize a temporary Git repository, configure filter.slow.clean, modify main.go, and run both probes (for the WaitDelay comparison below, stream_probe.go uses "--version" as the queued runner.Run argument and compares unmodified runner.go against setting cmd.WaitDelay = 100 * time.Millisecond in all four methods: Run, Output, RunSplit, and Stream):
go mod init repro
go build -o slowfilter.exe filter.go
$filterPath = (Resolve-Path .\slowfilter.exe).Path.Replace('\', '/')

$repo = Join-Path $PWD "fixture-repo"
New-Item -ItemType Directory -Force $repo | Out-Null
git -C $repo init
git -C $repo config user.name "test"
git -C $repo config user.email "[email protected]"
Set-Content -Path "$repo\main.go" -Value "package demo`nconst Version = 1`n"
git -C $repo add main.go
git -C $repo commit -m "init"

Set-Content -Path "$repo\.gitattributes" -Value "main.go filter=slow`n"
git -C $repo config filter.slow.clean $filterPath
Set-Content -Path "$repo\main.go" -Value "package demo`nconst Version = 3`n"

go run runner.go runsplit_probe.go $repo
go run runner.go stream_probe.go $repo
  1. Observe that the initial call remains blocked for over six seconds and the queued request cannot acquire the semaphore slot before its 200ms deadline.

Expected Behavior

Cancellation should finish within a bounded cleanup period and release the concurrency slot across Run, Output, RunSplit, and Stream. Incomplete Git output after cancellation or pipe-wait expiration should remain a failure, and Stream should not surface a raw closed-pipe read error in place of the cancellation failure.

Logs / Error Output

Initial RunSplit reproduction (200ms context timeout):

elapsed=6.505s context=context deadline exceeded command_error=exit status 1 stdout_bytes=157 stderr_bytes=0

Initial Stream reproduction (200ms context timeout, followed by a queued Run("status", "--porcelain") with a 200ms timeout):

context=context deadline exceeded semaphore_slots_held=1 queued_request=context deadline exceeded
stream_elapsed=6.169s stream_error=exit status 1

Follow-up Stream comparison (WaitDelay unset vs. cmd.WaitDelay = 100ms in all four Runner methods, 200ms stream timeout, followed by a synchronous queued Run("--version") with a 200ms timeout before reading done):

# Unmodified Runner (WaitDelay = 0)
context=context deadline exceeded semaphore_slots_held=1 queued_request=context deadline exceeded
stream_elapsed=6.333s stream_error=exit status 1

# With cmd.WaitDelay = 100ms
context=context deadline exceeded semaphore_slots_held=0 queued_request=exit status 1
stream_elapsed=404ms stream_error=read |0: file already closed

Additional Context

I'd like to work on a focused fix covering the shared Runner methods and cancellation regressions. Should the initial scope guarantee bounded return and error propagation only, or also descendant process-tree cleanup?

These need separate validation: in the WaitDelay = 100ms comparison above, stream_elapsed=404ms is measured after the synchronous queued Run call returns, so 404ms is an observed upper bound showing that by ~404ms Stream had already returned and released the semaphore slot (semaphore_slots_held=0) once os/exec closed the parent pipe. However, it does not verify that the helper subprocess itself exited early, and the current reproduction does not establish a permanent process leak.

#605 provides related WaitDelay handling for credential commands (where exec.ErrWaitDelay is ignored after a normal exit; in GitRunner, truncated Git output must remain an error). #1511 adds environment overrides to RunSplit; a fix here should preserve that interface. Broader MCP/ACP process-management changes would remain outside this proposal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions