Repository navigation
gitcmd: bound Wait after cancellation with WaitDelay - #1909
Conversation
|
✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s). |
|
Thanks for working on this. Reviewing head 1. High:
|
0039a94 to
31e87e9
Compare
|
Thanks for the detailed review — and you caught a real process mistake of mine. The On point 1 and the design recommendation: you're right, and my change is not sufficient for
I'd like to implement your recommended design rather than patch around it, since it changes the shape of all four methods:
Before I rewrite it: that is a substantially larger change than the current +16 lines, and it touches the |
|
Independent probes on Environment: macOS arm64, Go 1.26.10. Repository = A.
No improvement: B. A successful command with delayed descendant output now fails with
This is the success-path regression the recommended design avoids: So I'd +1 the proposed shape: For the record, the package suite is green on this head ( 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)
31e87e9 to
9717a3b
Compare
|
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
Honest limitation unchanged: this machine is Windows, so the alias tests compile ( cc @lizhengfeng101 — this implements the shape you recommended; happy to adjust. |
|
Re-ran this on macOS arm64, git 2.56.0, head
One blocker: two of the new tests are git-version/platform dependent and fail on macOS.
With those two skipped, 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)
|
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 Package suite still green on Windows, |
|
Confirmed on macOS arm64, git 2.56.0, head
From my side this is ready for review. (The GitHub workflows are still |
lizhengfeng101
left a comment
There was a problem hiding this comment.
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.
| } | ||
| }() | ||
| var once sync.Once | ||
| return func() { once.Do(func() { close(stopped) }) } |
There was a problem hiding this comment.
[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.
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| _, _ = io.Copy(&stderrBuf, errPipe.r) |
There was a problem hiding this comment.
[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)
|
Both findings confirmed and fixed in 1. Grace-callback teardown race. Your sequence is exactly right: 2. Unbounded stderr in New tests: Verification limits: this machine has no C compiler, so I cannot run |
|
@Batianxieshen1 Thanks for Before merging, could you please complete the remaining Windows verification and add the corresponding regression coverage?
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)
|
Both items are done in 1. Windows reproduction — measured on the exact new head. Environment: Windows 11 (10.0.26200), Fixture: the test binary re-executed through a git alias ( Observed (200 ms deadline, 100 ms grace):
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. The POSIX |
|
@Batianxieshen1 Thanks for the Windows measurements and the new tests in 1. The queued-request test is still sequentialIn 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 streamsBoth tests named 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. |
|
Both coverage mismatches confirmed and fixed in 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 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. Re-ran the affected tests on Windows (
Full Windows suite still green (26/26 packages). No production code changed in this commit. |
|
@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. ✅ Batianxieshen1 |
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.
f81eb46 to
77f93c6
Compare
|
@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 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. |
|
The only failing job on The 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? |
|
Thank you for rewriting the commit identity — that was my mistake and I appreciate the fix. The identity was meant to be |
Fixes #1907.
Problem
Run,Output,RunSplitandStreambuild their commands withexec.CommandContextand never setWaitDelay, so it keeps its default of zero. Peros/execthat makesWaitread the child's I/O pipes until EOF.exec.CommandContextkills 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 cancelledRunnercall blocks inWaituntil that orphan exits, holding its semaphore slot the whole time. The reporter measuredRunSplittaking 6.5 s andStream6.2 s under a 200 ms deadline, with a second request timing out behind the cancelled call.Change
Set
WaitDelayon all four command sites. It is a package var (not a const) so tests can shrink it, matchingkeyCmdWaitDelay/keyCmdTimeoutininternal/llm.This is the same failure
resolveKeyCmdalready 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.gohad no equivalent bound.5 * time.SecondmatcheskeyCmdWaitDelay. 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 -lreports nothing.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 !windowstag — the same tagkeycmd_test.gouses for itssleep-based cases.RunSplitover a repo whose clean filter backgroundssleep 30must return well under the orphan's lifetime, and a follow-up call on the same one-slotRunnermust 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
WaitDelayand watching them fail) therefore has not been run. The mechanism is documented byos/execand already proven in this repo byTestResolveKeyCmd_WaitDelayBoundsOrphanHoldingPipe— CI on Linux/macOS will confirm these.Impact
Cancellation path only. A call whose context is already done now costs at most
WaitDelayinstead of the orphan's lifetime. One behaviour change worth flagging: whenWaitDelaycloses pipes on a command that otherwise exited successfully,WaitreturnsErrWaitDelayrather thannil. The onlyStreamcaller (readLinesFromGitShow) fully drains stdout on the success path, so it never reaches that branch; on the paths that do, it already returns an error.