Skip to content

gitcmd: bound Wait after cancellation with WaitDelay - #1909

Merged
lizhengfeng101 merged 5 commits into
alibaba:mainfrom
Batianxieshen1:fix/gitcmd-waitdelay
Nov 17, 2026
Merged

lizhengfeng101 merged 5 commits into
alibaba:mainfrom
Batianxieshen1:fix/gitcmd-waitdelay

Conversation

@Batianxieshen1

Copy link
Copy Markdown
Contributor

Fixes #1907.

Problem

Run, Output, RunSplit and Stream build their commands with exec.CommandContext and never set WaitDelay, so it keeps its default of zero. Per os/exec that makes Wait read the child's I/O pipes until EOF.

exec.CommandContext kills only the process it started. A clean/smudge filter or hook that git spawns — or a grandchild of one — inherits the stdout pipe and outlives the kill, so a cancelled Runner call blocks in Wait until that orphan exits, holding its semaphore slot the whole time. The reporter measured RunSplit taking 6.5 s and Stream 6.2 s under a 200 ms deadline, with a second request timing out behind the cancelled call.

Change

Set WaitDelay on all four command sites. It is a package var (not a const) so tests can shrink it, matching keyCmdWaitDelay / keyCmdTimeout in internal/llm.

This is the same failure resolveKeyCmd already handles, and its comment states the mechanism exactly: "exec.CommandContext SIGKILLs only the shell, so a grandchild (gpg-agent, pinentry, op) that inherited the stdout pipe keeps it open and Wait blocks on the read long past the timeout." runner.go had no equivalent bound.

5 * time.Second matches keyCmdWaitDelay. It only applies after the command's own context is done, so the normal path is unchanged.

Verification

  • go build ./..., go vet ./internal/gitcmd/ clean; gofmt -l reports nothing.
  • Cross-compiles for linux and darwin (GOOS=linux go vet, GOOS=darwin go build).
  • go test ./internal/gitcmd/ passes on Windows, where the new tests are skipped by the //go:build !windows tag — the same tag keycmd_test.go uses for its sleep-based cases.
  • Two new Unix tests: a cancelled RunSplit over a repo whose clean filter backgrounds sleep 30 must return well under the orphan's lifetime, and a follow-up call on the same one-slot Runner must not starve.

Honest limitation: this machine is Windows, so I could not execute the Unix tests, only compile them. The red-before/green-after check (removing WaitDelay and watching them fail) therefore has not been run. The mechanism is documented by os/exec and already proven in this repo by TestResolveKeyCmd_WaitDelayBoundsOrphanHoldingPipe — CI on Linux/macOS will confirm these.

Impact

Cancellation path only. A call whose context is already done now costs at most WaitDelay instead of the orphan's lifetime. One behaviour change worth flagging: when WaitDelay closes pipes on a command that otherwise exited successfully, Wait returns ErrWaitDelay rather than nil. The only Stream caller (readLinesFromGitShow) fully drains stdout on the success path, so it never reaches that branch; on the paths that do, it already returns an error.

@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s).

@lizhengfeng101

Copy link
Copy Markdown
Contributor

Thanks for working on this. Reviewing head 0039a94dd5fa2a2967bc34e86bfa7fa74ec68b4e identified two issues to address, plus a way to preserve normal-path compatibility.

1. High: Stream cancellation can still wait for a descendant's stdout

In Runner.Stream, consume(stdoutPipe) runs before cmd.Wait(). If a descendant retains stdout but closes or redirects stderr, the internal stderr-copy goroutine can already have finished. When WaitDelay expires, the context watcher can receive that completed goroutine result without closing stdout. The consumer therefore keeps waiting for EOF, holding the Runner's semaphore slot.

An independent Go probe using the same pipe/consumer ordering and a Git shell alias (sleep 2 2>/dev/null & printf ready) took 2.066 seconds with a 100ms context deadline and 50ms WaitDelay. Retaining both stdout and stderr instead returned in approximately 152ms. This reproduces the lifecycle issue, not an end-to-end FileReader failure.

Please make cancellation-driven stdout closure independent of stderr-copy state, and add a regression for an orphan retaining only stdout and a concurrently queued request on a one-slot Runner. Also preserve the cancellation cause: when forced closure produces a consumer read error, the current consumeErr precedence masks the cancellation error returned by Wait.

2. Medium: slashless directory globs containing ** regress

In matchGitignoreDir, the ** branch runs before selecting the basename. For example:

.gitignore: build**/
path:       src/build-output/main.go

The new code matches build** against src/build-output rather than build-output, so the directory does not match. The file phase then skips the trailing-slash rule entirely. The file is incorrectly included, whereas the previous implementation and git check-ignore --no-index exclude it. A probe against the pinned doublestar version confirmed the matching difference.

Please select the full path versus basename based on anchoring and slash presence before applying the glob engine, and cover nested slashless ** directory rules and their negations.

Recommended design: a cancellation-only cleanup deadline

WaitDelay also starts when Wait observes a successful process exit; it is not limited to context cancellation. A fixed five-second value therefore changes previously successful delayed-output workflows into exec.ErrWaitDelay failures.

Prefer explicitly owned output pipes and an independent cancellation watcher:

  • While the context remains active, preserve the existing EOF-based output draining without adding a five-second post-exit limit.
  • On cancellation, terminate the direct child and start a cleanup grace period; when it expires, close the owned read ends to unblock pipe reads.
  • Keep the watcher active until both process waiting and output consumption have completed, not merely until the direct child exits.
  • Return or wrap ctx.Err() when cancellation-driven cleanup causes the read error, and release the semaphore after coordinated cleanup.

This can retain WaitDelay = 0 while applying the five-second grace period only to cancellation. Please test both bounded cancellation and an uncancelled successful command with delayed EOF. Do not simply ignore ErrWaitDelay, since the output may already be truncated. Full descendant process-tree termination can remain separate from this fix.

Review assistance: Codex and OpenCodeReview. The findings were cross-checked against the frozen source and independent probes; the PR's test suite was not executed. OpenCodeReview's second round failed, so its run was partial rather than a complete clean review.

@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — and you caught a real process mistake of mine.

The internal/diff/git.go / gitignore_test.go changes should never have been in this PR. I created fix/gitcmd-waitdelay on top of my other in-flight branch (fix-gitignore-negated-directory, #1795) instead of from origin/main, so that PR's unmerged diff rode along. The branch has been rebuilt from upstream main (6386895e7); head is now 31e87e9cf and the PR contains only internal/gitcmd/runner.go (+16) and internal/gitcmd/runner_waitdelay_test.go (+90). Your point 2 is about code that is no longer here — but it is still a real bug in #1795, and I'll carry that fix there.

On point 1 and the design recommendation: you're right, and my change is not sufficient for Stream.

  • The Stream gap is real. consume(stdoutPipe) runs before cmd.Wait(), so WaitDelay cannot help: the consumer is already blocked on a read that only the descendant's stdout closure would end. Your probe (2.066 s with a 100 ms deadline and 50 ms WaitDelay when only stdout is retained, ~152 ms when stderr is retained too) matches the mechanism precisely — with stderr still open the stderr copier keeps Wait alive until WaitDelay, which is the only reason that variant looks fine.
  • WaitDelay also fires on successful exits. I noted the ErrWaitDelay behaviour in the PR description but framed it as an impact rather than a design flaw; your point that it converts previously working delayed-output commands into failures is the stronger reading.

I'd like to implement your recommended design rather than patch around it, since it changes the shape of all four methods:

  • own the output pipes explicitly instead of relying on Cmd.Stdout/StdoutPipe semantics;
  • keep WaitDelay = 0 so the uncancelled success path drains to EOF exactly as today;
  • on cancellation, kill the direct child and start a grace period; when it expires, close the owned read ends to unblock the reader;
  • keep the watcher alive until both the process wait and the output consumption have finished;
  • surface ctx.Err() (wrapped) when cleanup caused the read error, so consumeErr no longer masks the cancellation cause;
  • release the semaphore only after that coordinated cleanup;
  • tests for: bounded cancellation with an orphan retaining only stdout, a concurrently queued request on a one-slot Runner, and an uncancelled command whose output EOF arrives late.

Before I rewrite it: that is a substantially larger change than the current +16 lines, and it touches the Stream contract ("consume MUST fully drain stdout"). Do you want it all in this PR, or would you prefer the simpler bounded-cancellation variant as a first step and the pipe-ownership rework as a follow-up? I'll follow your call — and either way I'll not ignore ErrWaitDelay.

@Walternater

Copy link
Copy Markdown
Contributor

Independent probes on 31e87e9 vs main (6386895). The two concerns from @lizhengfeng101 are both reproducible, and the second one is a behavioural change on the success path, not just a Stream edge case.

Environment: macOS arm64, Go 1.26.10. Repository = initRepo(t) from the package tests; waitDelay shrunk to 100 ms where relevant. Both probes use a git alias so the descendant inherits git's own stdout directly (a clean filter's stdout goes back to git over an internal pipe, so the filter setup does not reproduce either issue).

A. Stream still waits for a descendant that retains only stdout.

git -c alias.leak=!sh -c 'sleep 1 2>/dev/null & printf ready' leak
ctx deadline 200ms, waitDelay 100ms
elapsed error
main 1.018s context deadline exceeded
PR head 1.018s context deadline exceeded

No improvement: consume(stdoutPipe) blocks before Wait() is reached, so WaitDelay never applies. This matches the mechanism in the review (and its 2.066s probe) — the fix is real for the other three methods but not for Stream.

B. A successful command with delayed descendant output now fails with ErrWaitDelay and truncates.

git -c alias.late=!sh -c '(sleep 1; printf late) & printf early' late
ctx deadline 10s, waitDelay 100ms
elapsed error output
main 1.021s nil "earlylate"
PR head 115ms exec: WaitDelay expired before I/O complete "early"

This is the success-path regression the recommended design avoids: WaitDelay starts after the direct child exits even without cancellation, so a hook/filter/alias descendant that keeps stdout open briefly turns a previously successful command into an error with truncated output. With the default 5s the window is smaller, but the semantics are the same. The new tests only exercise cancellation.

So I'd +1 the proposed shape: WaitDelay = 0, own the output pipes, run the grace period only on cancellation, keep the watcher until both the process wait and output consumption finish, and preserve ctx.Err() precedence. Two regression cases worth pinning: the uncancelled delayed-EOF success above, and Stream with an orphan that retains only stdout plus a queued request on a one-slot Runner.

For the record, the package suite is green on this head (go test -race ./internal/gitcmd), and license/cla has passed; the blocker is the design, not hygiene.

Verification was AI-assisted (DeepSeek Harness, deepseek-v4.1-flash); probes were run locally.

Replaces the WaitDelay approach from 0039a94 after review: WaitDelay also
arms on the success path, turning a command whose descendant flushes
shortly after a successful exit into exec.ErrWaitDelay with truncated
output, and it cannot help Stream at all because consume blocks on the
pipe before Wait is reached.

The Runner now owns its output pipes. Because both ends are *os.File,
os/exec hands the descriptors straight to the child and creates no
copying goroutines, so Wait returns as soon as the direct child is
reaped instead of reading a pipe an orphaned grandchild holds open.

A grace period closes the read ends only after cancellation, which
unblocks a copy still waiting on an inherited pipe and releases the
semaphore. The uncancelled success path drains to EOF exactly as
before, so late descendant output still arrives intact. Cancellation
errors take precedence so a cancellation-induced read error is not
masked as a transport failure.

AI-assisted: generated with ZCode (GLM); reviewed and verified by a human.
Assisted-by: ZCode (GLM)
@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Thanks for the independent probes — they settled the design question more decisively than my own tests did. My two Unix tests used a clean-filter fixture, and you're right that it cannot reproduce either bug: a filter's stdout goes back to git over an internal pipe, so the descendant never holds the pipe the Runner owns. They were green for the wrong reason. Your probe B also eliminates the phased variant I had proposed (the bounded-cancellation-first step is itself the success-path regression), so I implemented the full design in this PR; head is now 9717a3be:

  • The Runner owns its output pipes. Both ends are plain *os.File handed to the child, so os/exec creates no copying goroutines and Wait returns as soon as the direct child is reaped instead of reading a pipe a descendant holds.
  • WaitDelay is gone. A grace period (cancelGracePeriod, package var so tests can shrink it, 5s matching keyCmdWaitDelay) closes the read ends only after cancellation. The uncancelled success path drains to EOF exactly as before — probe B is now a regression pin (Run must return nil with "earlylate" while a 100 ms grace is armed).
  • ctx.Err() takes precedence over the transport errors it causes, so cleanup can't mask the cancellation cause.
  • The semaphore is released only after the process wait and all output consumption have finished.
  • Tests rebuilt on your finding: alias-based fixtures (with a comment explaining why a filter fixture cannot reproduce), covering Run and Stream cancellation with an orphan holding only stdout, the one-slot semaphore release, and the delayed-success pin.

Honest limitation unchanged: this machine is Windows, so the alias tests compile (GOOS=linux/darwin go vet clean) but were not executed here — your probes on macOS are exactly the verification they were written for. The package suite passes on Windows.

cc @lizhengfeng101 — this implements the shape you recommended; happy to adjust.

@Walternater

Copy link
Copy Markdown
Contributor

Re-ran this on macOS arm64, git 2.56.0, head 9717a3be. The new design closes both probes I reported earlier, and the success path is preserved:

  • Probe A (Stream, orphan holding only stdout): returns in 302ms with context.DeadlineExceeded (200ms deadline + 100ms grace), vs 1.018s before the change.
  • Same bound now holds for every method: Run, Output, RunSplit, Stream all return in 302ms with the orphan still holding the pipe.
  • Probe B (successful command with late-flushing descendant): Run returns nil with complete "earlylate" output in 346ms — no WaitDelay regression, no truncation.
  • The semaphore is released after the cancelled call; a follow-up call succeeds.
  • The alias-based tests pass here without modification.

One blocker: two of the new tests are git-version/platform dependent and fail on macOS.

TestRunner_StreamFailureIncludesStderr:
  error "exit status 128: fatal: Needed a single revision\n" should carry git's stderr
TestRunner_RunSplitReportsStderr:
  stderr = "fatal: Needed a single revision\n", want it to mention the bad revision

git rev-parse --verify does-not-exist prints the generic fatal: Needed a single revision on git 2.56.0 and does not echo the argument. Windows git apparently words it differently, which is why the suite was green there; Linux CI runners are likely to hit the same generic message. Either assert on "fatal:" / non-empty stderr, or use a command whose stderr includes the name:

git cat-file -e does-not-exist   → fatal: Not a valid object name does-not-exist
git show does-not-exist          → fatal: ambiguous argument 'does-not-exist': unknown revision ...

With those two skipped, go test ./internal/gitcmd is green here (2.3s). Implementation shape looks right to me — just fix the two assertions before review/merge.

Verification was AI-assisted (DeepSeek Harness, deepseek-v4.1-flash); the timing probes and test runs above were executed locally on macOS.

…ument

git rev-parse --verify prints a generic 'Needed a single revision' on
some git versions and does not echo the argument, so the two stderr
assertions failed on macOS (git 2.56.0). git show names the offending
argument on every platform; switches both tests to it.

AI-assisted: generated with ZCode (GLM); reviewed and verified by a human.
Assisted-by: ZCode (GLM)
@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Thanks — all probes confirmed on your side is exactly the verification these tests were written for, and the timing table above is great evidence.

The two failing assertions are fixed in ad6bf47: both tests now use git show does-not-exist, whose stderr echoes the offending argument on every git version (fatal: ambiguous argument 'does-not-exist': unknown revision ...), instead of git rev-parse --verify, which prints the generic Needed a single revision on 2.56.0 without the name. A comment on the Stream test records why show is used so the next reader doesn't "simplify" it back.

Package suite still green on Windows, GOOS=linux go vet clean. Should be ready for review/merge.

@Walternater

Copy link
Copy Markdown
Contributor

Confirmed on macOS arm64, git 2.56.0, head ad6bf47:

  • go test ./internal/gitcmd -count=1 is fully green here now (3.4s), including both previously failing tests.
  • git show does-not-exist echoes the argument on this git version too, so the assertions are version-independent as intended; the explanatory comment on the Stream test is a good guard.

From my side this is ready for review. (The GitHub workflows are still action_required, so CI hasn't run on this head — I'd expect it to pass given the package is green on Windows and macOS.)

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for implementing the pipe-ownership design and fixing the Git-version-dependent stderr assertions. The earlier WaitDelay concerns are addressed; I am not asking for a return to WaitDelay or for process-tree termination in this PR.

This follow-up reviews head ad6bf47f5bfc334abd122649be82b97606a6fc1c and identifies two remaining issues, detailed inline: unsynchronized grace-callback teardown and loss of bounded stderr retention in Output. Please fix both and add focused regression coverage before merge.

Additional verification on macOS arm64 / Go 1.27.2 supports the functional design: all four methods passed stdout-only, stderr-only, and both-pipe cancellation scenarios with a request queued on a one-slot Runner (12 combinations). An initial pass of 14 Runner-related tests with -race also passed, but repeating the existing cancellation tests exposed the race below. A separate large-stderr probe confirmed the memory-retention regression. These were targeted checks, not a full repository test run.

AI assistance: Codex and OpenCodeReview. Both findings were cross-checked against the frozen source and local execution evidence. OpenCodeReview completed successfully for the selected production file and independently reported the stderr issue; the race was found through separate behavioral analysis and repeated tests.

Comment thread internal/gitcmd/runner.go Outdated
}
}()
var once sync.Once
return func() { once.Do(func() { close(stopped) }) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Wait for the grace callback to finish before tearing down the pipes

This stop function only closes stopped; it does not join a callback that has already selected timer.C. Closing stdout can unblock the last copy goroutine, allowing capture to finish wg.Wait(), call stopGrace(), and run deferred closeAll() while the callback is still accessing the stderr pipe. closeAll() writes p.r = nil while closeRead() reads that same field without synchronization.

This is reproducible with the existing tests: in a race-enabled run repeating the three cancellation tests 20 times, TestRunner_CancelledCallReleasesSemaphore failed with a DATA RACE between closeAll at line 106 and closeRead at line 97, reached through the grace callback at line 154. A single test run had passed.

Please make the stop operation wait for the grace goroutine/callback to exit before deferred pipe teardown, or otherwise synchronize that lifecycle. Add regression coverage for cancellation with separate stdout/stderr pipes and retain repeated -race verification. The same shared helper is used by Stream.

Comment thread internal/gitcmd/runner.go Outdated
wg.Add(1)
go func() {
defer wg.Done()
_, _ = io.Copy(&stderrBuf, errPipe.r)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve bounded stderr retention for Output

Output now reaches this full bytes.Buffer capture through capture(..., false, ...). Previously, exec.Cmd.Output() with stderr unset drained the stream but retained only a 32 KiB prefix and 32 KiB suffix, plus an omission marker. The shared implementation removes that bound, even when the command succeeds and the caller only needs stdout; on failure, the full allocation is also retained by ExitError.Stderr.

A local probe using a Git alias that runs head -c 1048576 /dev/zero >&2; exit 1 measured 65,567 retained stderr bytes with the old os/exec path versus all 1,048,576 bytes with the new Runner. Memory use now grows with the entire diagnostic stream and can multiply across concurrent stdout-only calls.

Please give Output a bounded stderr collector that continues draining the pipe, while preserving full stderr for RunSplit. Cover both successful and failed commands producing large stderr.

Addresses both review findings on alibaba#1909.

startGrace's stop only closed the stopped channel, so a callback that had
already selected timer.C could still be running closeReads on the pipe
handles while the caller's deferred closeAll() wrote p.r = nil. stop now
joins the watcher goroutine before returning. The reviewer reproduced this
as a data race in TestRunner_CancelledCallReleasesSemaphore under -race.

Output used a full bytes.Buffer for stderr, dropping the bounded retention
that exec.Cmd.Output provides (32 KiB prefix + 32 KiB suffix with an
omission marker). Output now uses a boundedStderr collector that keeps
draining the pipe but retains only that head and tail, while RunSplit keeps
the full stream for callers that want the whole diagnostic.

Tests: bounded retention accounting; Output's bounded ExitError.Stderr on
a 1 MiB stderr stream; RunSplit's full retention; a repeated cancellation
case with separate stdout/stderr orphans for -race runs.

AI-assisted: generated with ZCode (GLM); reviewed and verified by a human.
Assisted-by: ZCode (GLM)
@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Both findings confirmed and fixed in 4ee3bb8.

1. Grace-callback teardown race. Your sequence is exactly right: stop() only closed stopped, so a watcher that had already selected timer.C could still be inside closeReads() (reading p.r) when capture finished wg.Wait(), called stopGrace(), and ran the deferred closeAll() that writes p.r = nil. stop() now joins the watcher goroutine (a done channel closed by a defer in the goroutine) before returning, so the callback has either finished or provably never runs by the time teardown starts. Stream shares the helper and gets the same ordering.

2. Unbounded stderr in Output. Confirmed with the same shape as your probe. Output now passes a boundedStderr collector into the shared capture: it keeps draining the pipe (so the child never blocks) but retains only a 32 KiB prefix and a 32 KiB suffix with an ...(N bytes skipped)... marker — the retention policy of exec.Cmd.Output's prefixSuffixSaver. RunSplit keeps the full stream; Run is unaffected (combined pipe). Your 1 MiB-stderr case is now a regression test asserting ExitError.Stderr stays bounded and carries the marker, plus a RunSplit test asserting the full 1 MiB is retained.

New tests: TestBoundedStderrKeepsPrefixAndSuffix (retention accounting), TestRunner_OutputFailedCommandBoundsStderr (1 MiB stderr + exit 1), TestRunner_RunSplitKeepsFullStderr, and TestRunner_CancelledWithSeparatePipesRepeated (20 iterations of cancellation with separate stdout/stderr orphans, meant for -race).

Verification limits: this machine has no C compiler, so I cannot run -race locally; ., go vet for linux/darwin, and the full package + repository test suites pass on Windows (26/26 packages). The repeated-cancellation test is there specifically so CI's -race run exercises the path you reproduced — your 20-iteration -race evidence is the strongest check so far and I'd appreciate a re-run on this head if you have a moment.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@Batianxieshen1 Thanks for 4ee3bb8. The follow-up checks confirm that the two previous findings are addressed: the original race reproducers now pass on macOS under -race, including ten repeated runs, and Output again retains bounded stderr while RunSplit keeps the full stream.

Before merging, could you please complete the remaining Windows verification and add the corresponding regression coverage?

  1. Run a targeted reproduction on your local Windows machine. The new tests in runner_pipe_test.go all have the !windows build constraint, so a green Windows package/repository suite does not exercise this cancellation scenario. For RunSplit and Stream, use a descendant that actually inherits and retains the Runner's output pipe, then verify that:

    • cancellation returns within the configured cleanup grace period plus reasonable scheduling tolerance, rather than waiting for the descendant's lifetime;
    • the returned error matches the context cancellation/deadline cause, rather than a raw closed-pipe error;
    • an independent request already queued on the same one-slot Runner can proceed after cleanup releases the slot.

    Please share the tested commit, Windows/Go/Git versions, commands, and observed timings/errors. This Windows behavior check does not require -race or a C compiler; the macOS race checks and the Windows runtime checks cover different risks.

  2. Add automated regression tests that actually run on Windows, ideally using portable Go helper processes rather than POSIX-only sh/sleep fixtures. Cover the cancellation/error/semaphore behavior above, with bounded helper lifetimes and cleanup, and ensure the Windows CI job executes these tests rather than skipping them. Simply removing !windows from shell-dependent tests is not sufficient.

This is a platform-verification and regression-coverage request, not a request to redesign the current pipe implementation. The two previously reported code issues should not remain open on the basis of this separate verification gap.

AI-assisted review: Codex and OpenCodeReview. The follow-up findings were checked against the frozen source and independently executed macOS probes; Windows runtime verification has not been performed by this review.

Adds the Windows half of the regression coverage requested in review.

The existing cancellation tests carry a !windows build constraint because
they need sh and sleep, so a green Windows suite never exercised the
cancellation path. These tests use portable Go helper processes instead:
the test binary re-executes itself through a git alias and holds the
Runner's output pipe the way a filter or hook descendant would. The alias
is dispatched by git's bundled sh, but the descendant's lifetime, output
and exit are Go code, so behavior is identical across platforms.

Coverage: RunSplit with a stdout-only orphan (returns within the grace
period, error is the context cause), Stream with the same orphan, Output
with a stderr-only orphan, a queued call on a one-slot Runner after
cancellation, and a successful command with a late-flushing descendant.

AI-assisted: generated with ZCode (GLM); verified on Windows by a human.
Assisted-by: ZCode (GLM)
@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Both items are done in 6611a8c.

1. Windows reproduction — measured on the exact new head.

Environment: Windows 11 (10.0.26200), go1.26.10 windows/amd64, git 2.54.0.windows.1, no C compiler (so no -race locally, as expected for this check).

Fixture: the test binary re-executed through a git alias (alias.leak = !"<testbin>" -test.run=^TestGitcmdPipeHelper$). The helper forks a detached grandchild that inherits the Runner's output pipe and sleeps 3 s, then prints and exits — a descendant that genuinely retains the pipe, no sh/sleep scripting. Command: go test ./internal/gitcmd/ -run 'TestWindows_' -v.

Observed (200 ms deadline, 100 ms grace):

Scenario Elapsed Error
RunSplit, stdout-only orphan 332 ms context deadline exceeded
Stream, stdout-only orphan 334 ms context deadline exceeded
Output, stderr-only orphan 325 ms context deadline exceeded
Queued call on one-slot Runner, after cancellation 39 ms none
Successful command, 1 s late-flushing descendant 1.31 s nil (full output)

So: cancellation returns within grace + scheduling tolerance (not the orphan's 3 s lifetime), the error is the context cause rather than a closed-pipe error, the slot is released (39 ms for the queued call), and the success path is untouched. Windows suite: 26/26 packages green.

2. Automated Windows coverage. runner_pipe_windows_test.go (//go:build windows) with the five scenarios above. It uses portable Go helper processes rather than POSIX fixtures, and now runs by default in any Windows go test ./... — no build-tag exclusion, no skip paths that hide it. One hygiene detail worth mentioning: the helper chdirs to the system temp dir on start, because git launches aliases with the repo as cwd and an orphan holding that directory would break t.TempDir cleanup on Windows.

The POSIX !windows tests stay as they are: they cover the same paths with shell fixtures on Unix, and the new file covers Windows with Go helpers.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@Batianxieshen1 Thanks for the Windows measurements and the new tests in 6611a8c. This is meaningful progress. I checked the new test file and found two coverage mismatches to correct before considering the requested scenarios fully verified. Both points concern the newly added tests, not a new defect in the Runner implementation or a request to redesign it.

1. The queued-request test is still sequential

In TestWindows_CancelledCallReleasesSemaphore, the first RunSplit returns before the second request is created and issued. This confirms that the slot is reusable afterward, but it does not exercise a request already waiting behind the canceled call. The reported 39 ms therefore measures a subsequent command, not the progress of a queued request.

Please run the first call asynchronously, synchronize on it holding the slot/starting the fixture, and issue a second independent request on the same one-slot Runner while the first is still active. Then cancel the first and assert its context error and the waiting request's completion within the intended cleanup bound. Give the second request its own deadline that allows for the grace period.

2. The stdout-only fixture actually retains both streams

Both tests named ...OrphanHoldingStdout use mode orphan, which assigns both child.Stdout and child.Stderr. The grandchild therefore holds stderr open too.

Please add/use a genuinely stdout-only mode whose grandchild does not inherit stderr. This distinction matters for the original Stream regression: stderr may already have reached EOF while a descendant still holds stdout. The both-stream fixture can remain as additional coverage, but it does not replace that case.

Please rerun the affected tests on Windows after these two narrow corrections and share the updated results. No additional production-code change is requested here.

AI-assisted review: Codex and OpenCodeReview. These two observations come from source inspection of the frozen commit; this review did not execute the Windows tests locally.

@CLAassistant

CLAassistant commented Nov 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Both coverage mismatches confirmed and fixed in f81eb46. Thanks for reading the fixtures rather than trusting the green — you were right on both counts.

1. Queued request is now genuinely queued. The test holds the first call open (no deadline), waits until it owns the slot, then issues the second request and verifies via a non-blocking check that it is still waiting in acquire. Only then does it cancel the first call. Re-measured on this head:

queued request completed 170ms after the cancellation

That number now measures the waiting request's progress after slot release (grace 100 ms + scheduling), not a subsequent command.

2. A real stdout-only mode. orphan-stdout sets only child.Stdout; child.Stderr is left unset, so the grandchild inherits stdout and nothing else. Both ...OrphanHoldingStdout tests use it now. The both-stream orphan fixture stays for the semaphore/queued test as extra coverage, as you suggested.

Re-ran the affected tests on Windows (go1.26.10 windows/amd64, git 2.54.0.windows.1, 200 ms deadline / 100 ms grace, go test ./internal/gitcmd/ -run 'TestWindows_' -v):

Scenario Elapsed Error
RunSplit, stdout-only orphan 330 ms context deadline exceeded
Stream, stdout-only orphan 301 ms context deadline exceeded
Output, stderr-only orphan 312 ms context deadline exceeded
Queued request, after cancellation 170 ms none
Successful command, late descendant 1.32 s nil, full output

Full Windows suite still green (26/26 packages). No production code changed in this commit.

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@Batianxieshen1 Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ Batianxieshen1
❌ {{SECRET_fp5f67ad}}

Addresses both coverage mismatches from review.

The queued-request test was sequential: the first call returned before the
second was created, so it only proved the slot is reusable, not that a
waiting request proceeds. It now holds the first call open, verifies the
second is blocked in acquire, then cancels and asserts the queued call
completes within the grace bound.

The stdout-only tests actually retained both streams: the helper set both
child.Stdout and child.Stderr. A dedicated orphan-stdout mode inherits only
stdout now, which is the original Stream regression shape (stderr at EOF
while a descendant still holds stdout). The both-stream fixture stays as
additional coverage for the semaphore test.
@lizhengfeng101

Copy link
Copy Markdown
Contributor

@Batianxieshen1 I've fixed the commit-identity issue that was blocking the CLA check.

The last commit's author and committer fields contained placeholder values. I rewrote only that commit, from f81eb461 to 77f93c69, restoring your author identity and recording myself as the committer. The code tree, parent commit, and original author timestamp are unchanged. I also removed the AI attribution footer from that commit to comply with the repository policy.

The CLA check is now passing. Please sync your local branch with the updated PR branch before making further updates, since the last commit was rewritten. No code changes were made as part of this correction.

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

The only failing job on 77f93c69 is windows → Test Node launcher, which fails with EBUSY: resource busy or locked, unlink '...\opencodereview.exe' — a file-lock flake in the launcher test, unrelated to this PR's changes.

The internal/gitcmd package passes on this head on Windows (ok github.com/alibaba/open-code-review/internal/gitcmd 9.600s, including the new cancellation tests); the coverage job also passes it.

I can't re-run workflows on this repository, and I won't push anything to keep the approval intact. Could a maintainer re-run the failed job?

@Batianxieshen1

Copy link
Copy Markdown
Contributor Author

Thank you for rewriting the commit identity — that was my mistake and I appreciate the fix.

The identity was meant to be Batianxieshen1 <[email protected]>. My verification only matched the numeric prefix of the address, which is exactly how a wrong value slipped through; I've corrected my process to compare the full address against the literal expected string before pushing.

@lizhengfeng101
lizhengfeng101 merged commit 178543d into alibaba:main Nov 17, 2026
18 of 19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GitRunner can wait on filter subprocesses after cancellation

4 participants