Skip to content

os: File.Close can hang when used with non-overlapped pipes on Windows #64482

Closed

Description

@gopherbot
#!watchflakes
post <- goos == "windows" && pkg == "os" &&
    ((log ~ `panic: test timed out` && log ~ `^\s*syscall\.CancelIoEx`) ||
     status == "ABORT" ||
     (test == "TestPipeIOCloseRace" && status == "SKIP"))

Issue created automatically to collect these failures.

Example (log):

panic: test timed out after 3m0s
running tests:
	TestPipeIOCloseRace (2m59s)

goroutine 879 gp=0x4000174340 m=10 mp=0x4000180708 [running]:
panic({0x7ff7b437a3a0?, 0x4000400040?})
	C:/workdir/go/src/runtime/panic.go:779 +0x140 fp=0x400017bf00 sp=0x400017be50 pc=0x7ff7b4229d10
testing.(*M).startAlarm.func1()
	C:/workdir/go/src/testing/testing.go:2366 +0x30c fp=0x400017bfd0 sp=0x400017bf00 pc=0x7ff7b42f001c
runtime.goexit({})
...

goroutine 273 gp=0x4000443860 m=nil [GC worker (idle), 2 minutes]:
runtime.gopark(0x8501acdde81b4?, 0x0?, 0x0?, 0x0?, 0x0?)
	C:/workdir/go/src/runtime/proc.go:402 +0xc8 fp=0x400034bf30 sp=0x400034bf10 pc=0x7ff7b422d398
runtime.gcBgMarkWorker()
	C:/workdir/go/src/runtime/mgc.go:1310 +0xd8 fp=0x400034bfd0 sp=0x400034bf30 pc=0x7ff7b420c1c8
runtime.goexit({})
	C:/workdir/go/src/runtime/asm_arm64.s:1222 +0x4 fp=0x400034bfd0 sp=0x400034bfd0 pc=0x7ff7b4263734
created by runtime.gcBgMarkStartWorkers in goroutine 308
	C:/workdir/go/src/runtime/mgc.go:1234 +0x28

— watchflakes

Activity

  1. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Nov 30, 2023
  2. gopherbot commented on Nov 30, 2023

    @gopherbot
    ContributorAuthor

    Found new dashboard test flakes for:

    #!watchflakes
    default <- pkg == "os" && test == ""
    
    2023-11-30 18:35 windows-arm64-11 go@bda1ef13 os (log)
    panic: test timed out after 3m0s
    running tests:
    	TestPipeIOCloseRace (2m59s)
    
    goroutine 879 gp=0x4000174340 m=10 mp=0x4000180708 [running]:
    panic({0x7ff7b437a3a0?, 0x4000400040?})
    	C:/workdir/go/src/runtime/panic.go:779 +0x140 fp=0x400017bf00 sp=0x400017be50 pc=0x7ff7b4229d10
    testing.(*M).startAlarm.func1()
    	C:/workdir/go/src/testing/testing.go:2366 +0x30c fp=0x400017bfd0 sp=0x400017bf00 pc=0x7ff7b42f001c
    runtime.goexit({})
    ...
    
    goroutine 273 gp=0x4000443860 m=nil [GC worker (idle), 2 minutes]:
    runtime.gopark(0x8501acdde81b4?, 0x0?, 0x0?, 0x0?, 0x0?)
    	C:/workdir/go/src/runtime/proc.go:402 +0xc8 fp=0x400034bf30 sp=0x400034bf10 pc=0x7ff7b422d398
    runtime.gcBgMarkWorker()
    	C:/workdir/go/src/runtime/mgc.go:1310 +0xd8 fp=0x400034bfd0 sp=0x400034bf30 pc=0x7ff7b420c1c8
    runtime.goexit({})
    	C:/workdir/go/src/runtime/asm_arm64.s:1222 +0x4 fp=0x400034bfd0 sp=0x400034bfd0 pc=0x7ff7b4263734
    created by runtime.gcBgMarkStartWorkers in goroutine 308
    	C:/workdir/go/src/runtime/mgc.go:1234 +0x28
    

    — watchflakes

  3. changed the title [-]os: unrecognized failures[/-] [+]os: TestPipeIOCloseRace timeout on Windows blocked in `syscall.CancelIoEx`[/+] on Nov 30, 2023
  4. bcmills commented on Nov 30, 2023

    @bcmills
    Contributor

    @golang/windows, any idea why CancelIoEx would block for over 2 minutes?

  5. added this to the Backlog milestone on Nov 30, 2023
  6. moved this to Active in Test Flakeson Nov 30, 2023
  7. alexbrainman commented on Dec 8, 2023

    @alexbrainman
    Member

    @golang/windows, any idea why CancelIoEx would block for over 2 minutes?

    No idea. According to https://learn.microsoft.com/en-us/windows/win32/fileio/cancelioex-func

    The CancelIoEx function does not wait for all canceled operations to complete.

    Alex

  8. gopherbot commented on Mar 12, 2024

    @gopherbot
    ContributorAuthor

    Found new dashboard test flakes for:

    #!watchflakes
    post <- goos == "windows" && pkg == "os" && ((log ~ `panic: test timed out` && log ~ `^\s*syscall\.CancelIoEx`) || status == "ABORT" )
    
    2024-03-07 05:26 gotip-windows-386 go@a0624701 os.TestPipeIOCloseRace [ABORT] (log)
    === RUN   TestPipeIOCloseRace
    === PAUSE TestPipeIOCloseRace
    === CONT  TestPipeIOCloseRace
    

    — watchflakes

  9. gopherbot commented on Feb 22, 2025

    @gopherbot
    ContributorAuthor

    Found new dashboard test flakes for:

    #!watchflakes
    post <- goos == "windows" && pkg == "os" && ((log ~ `panic: test timed out` && log ~ `^\s*syscall\.CancelIoEx`) || status == "ABORT" )
    
    2025-02-22 21:25 gotip-windows-arm64 go@38825ef3 os.TestPipeIOCloseRace [ABORT] (log)
    === RUN   TestPipeIOCloseRace
    === PAUSE TestPipeIOCloseRace
    === CONT  TestPipeIOCloseRace
    

    — watchflakes

  10. self-assigned this
    on Mar 28, 2025
  11. wiresock commented on Jun 20, 2025

    @wiresock

    Hello!

    I extracted the test from this issue and turned it into a standalone application. It consistently hangs under load, and after digging into the cause, I believe the root issue is in how Go handles pipe cleanup on Windows.

    Specifically, os.Pipe() uses CreatePipe, which creates synchronous handles (i.e., not created with FILE_FLAG_OVERLAPPED). However, in (*FD).Close() Go still calls:

    if fd.kind == kindPipe {
        syscall.CancelIoEx(fd.Sysfd, nil)
    }

    This is unsafe because CancelIoEx is designed for canceling overlapped I/O, not synchronous I/O. Calling it on a synchronous pipe handle can lead to hangs.

    After commenting out that call and rebuilding Go from source, the hang completely disappeared.

    So this is an issue in the runtime: Go calls CancelIoEx on handles where it's neither needed nor safe. A fix could be to avoid calling CancelIoEx unless the handle was explicitly created with FILE_FLAG_OVERLAPPED.

    I actually stepped into this issue while investigating another CancelIoEx-related hang, which occurs at this line. Any ideas on that one?

  12. wiresock commented on Jul 4, 2025

    @wiresock

    Hello @qmuntal,

    To add more technical detail: the hang happens when a thread issues two I/Os—first an async IO, then a sync IO (which blocks with normal kernel APCs disabled). If another thread then tries to cancel the async IO, the IO manager does not call KeAlertThread because the thread is blocked in a state where normal kernel APCs can’t be delivered. As a result, the cancel APC is never processed, and the thread is stuck indefinitely.

    In general, a single thread should not mix synchronous and asynchronous I/O, especially on Windows, to avoid these low-level kernel issues. It would be great if the Go runtime could be audited for any such cases.

    Just to clarify: in the case of os.Pipe(), there isn’t an actual asynchronous I/O in play, but calling CancelIoEx on a synchronous pipe handle still triggers the same underlying scenario.

    Internally, CancelIoEx queues a kernel APC to the target thread. But if that thread is currently blocked on a synchronous I/O operation (with normal kernel APCs disabled), the APC can’t be delivered, and the IO manager doesn’t invoke KeAlertThread. As a result, the thread gets stuck in an uninterruptible wait.

    So even without async IO, calling CancelIoEx on a synchronous pipe handle is unsafe and can lead to a hang.

  13. qmuntal commented on Jul 4, 2025

    @qmuntal
    Member

    Thanks for this detailed information @wiresock, what you say makes sense and it is really useful.

    On the other hand, that CancelIoEx call was put there to in d227a08 to fix several other issues, so we can't just remove it.

    I'll try to fix this for Go 1.26 (although any help is welcomed).

  14. wiresock commented on Jul 24, 2025

    @wiresock

    Thanks for the clarification, @qmuntal.

    To assist further, here’s a detailed analysis from the Microsoft Kernel team on this scenario. It confirms that when a thread performs synchronous I/O (e.g., ReadFile or WriteFile) on a named pipe, normal kernel APC delivery is disabled during the wait. As a result, any thread attempting to cancel that I/O using CancelIoEx will block indefinitely, waiting for an APC that can’t be delivered.

    Microsoft explicitly warns not to mix sync and async I/O on the same handle or thread. If cancellation is needed for sync I/O, CancelSynchronousIo should be used instead.

    In the hangtest.exe, thread (ffffa2029d6c3080) is waiting on Sync IO for WriteFile on FileObject (ffffa2029f495670) for Named Pipe and as this is a synchronous wait normal kernel APCs are disabled.
    We have another thread (ffffa2029f0d7080) for CancelIoEx() which is trying to cancel the IO on the FileObject (0xffffa202`9f494d10) for Named Pipe against the thread (ffffa2029d6c3080) and this has queued normal Kernel APC to cancel the IRPs and waiting for the APC execution.
    This wont progress as normal Kernel APC is disabled on the thread (ffffa2029d6c3080) because of Sync IO Wait.

    As stated earlier, it is critical not to mix and match Sync and Async IO. To cancel the Sync IO on a thread use CancelSynchronousIo() as stated in the documentation here.

    Process                         Thread           CID       UserTime KernelTime ContextSwitches Wait Reason      Time State
    hangtest.exe (ffffa202a18f0080) ffffa2029d6c3080 2d38.1cd0     63ms      344ms            3380 Executive   9m:35.406 Waiting
    
    Irp List:
        IRP              File   Driver Owning Process
        ffffa202a47f2b00 (null) Npfs   hangtest.exe
    
    # Child-SP         Return           Call Site
    0 ffffe881ff1f7e70 fffff8067f02a4d0 nt!KiSwapContext+0x76
    1 ffffe881ff1f7fb0 fffff8067f0299ff nt!KiSwapThread+0x500
    2 ffffe881ff1f8060 fffff8067f0292a3 nt!KiCommitThreadWait+0x14f
    3 ffffe881ff1f8100 fffff8067f1f1744 nt!KeWaitForSingleObject+0x233
    4 ffffe881ff1f81f0 fffff8067f406d96 nt!IopWaitForSynchronousIoEvent+0x50
    5 (Inline)         ---------------- nt!IopWaitForSynchronousIo+0x23
    6 ffffe881ff1f8230 fffff8067f3cfdb5 nt!IopSynchronousServiceTail+0x466
    7 ffffe881ff1f82d0 fffff8067f487ec0 nt!IopWriteFile+0x23d
    8 ffffe881ff1f83d0 fffff8067f212005 nt!NtWriteFile+0xd0
    9 ffffe881ff1f8450 00007fffdb70d5f4 nt!KiSystemServiceCopyEnd+0x25
    a 00000055e4fff638 0000000000000000 0x7fffdb70d5f4
    
    Irp Details: ffffa202a47f2b00
        Thread           Process      Frame Count
        ============================= ===========
        ffffa2029d6c3080 hangtest.exe           2
    
    Irp Stack Frame(s)
          # Driver           Major Minor Dispatch Routine Flg Ctrl Status  Device           File                                                            
        === ================ ===== ===== ================ === ==== ======= ================ ================
        ->2 \FileSystem\Npfs WRITE     0 IRP_MJ_WRITE       0    1 Pending ffffa202987985f0 ffffa2029f495670
    
    ================================================================
    ffffa2029f495670 
    Related File Object: 0xffffa2029f494d10 
    Device Object: 0xffffa202987985f0   \FileSystem\Npfs
    Vpb is NULL
    
    Flags:  0x40082
      Synchronous IO
      Named Pipe
      Handle Created
    

    File Object is currently busy and has 0 waiters.

    FsContext: 0xffffc40ddc15a8c0      FsContext2: 0xffffc40ddc6bb291
    Private Cache Map: 0x00000001
    CurrentByteOffset: 0
    
     
    Process                         Thread           CID       UserTime KernelTime ContextSwitches Wait Reason      Time State
    hangtest.exe (ffffa202a18f0080) ffffa2029f0d7080 2d38.241c     31ms      391ms            4151 Executive   9m:35.406 Waiting
    
    # Child-SP         Return           Call Site
    0 ffffe881fedd8fe0 fffff8067f02a4d0 nt!KiSwapContext+0x76
    1 ffffe881fedd9120 fffff8067f0299ff nt!KiSwapThread+0x500
    2 ffffe881fedd91d0 fffff8067f0292a3 nt!KiCommitThreadWait+0x14f
    3 ffffe881fedd9270 fffff8067f4a72dd nt!KeWaitForSingleObject+0x233
    4 ffffe881fedd9360 fffff8067f5218dc nt!IopCancelIrpsInThreadList+0x125
    5 ffffe881fedd93b0 fffff8067f4a70d6 nt!IopCancelIrpsInThreadListForCurrentProcess+0xc4
    6 ffffe881fedd9470 fffff8067f212005 nt!NtCancelIoFileEx+0xc6
    7 ffffe881fedd94c0 00007fffdb70e724 nt!KiSystemServiceCopyEnd+0x25
    8 00000055e45ffc88 0000000000000000 0x7fffdb70e724
    
    This thread has been waiting 9m:35.406 on a kernel component request
    
    ===============================================================
    
    0xffffa2029f494d10
    
    Related File Object: 0xffffa2029fb0dd60 
    Device Object: 0xffffa202987985f0   \FileSystem\Npfs
    Vpb is NULL
    Event signalled
    
    Flags:  0x40082
      Synchronous IO
      Named Pipe
      Handle Created
    

    The dump of reducted_executable_name.exe follows the same pattern.

    Thread (0xffffaf8602c90080) is waiting on Sync IO for ReadFile on FileObject (ffffaf86107074b0) for Named Pipe and as this is a synchronous wait normal kernel APCs are disabled. We have another thread (ffffaf8602d06080) for CancelIoEx() which is trying to cancel the IO on the FileObject (0xffffaf8611746570) for AFD endpoints (Kernel driver for sending and receiving network data from/to tcpip.sys) against the thread (0xffffaf8602c90080) and this has queued normal Kernel APC to cancel the IRPs and waiting for the APC execution. This won’t progress as normal Kernel APC is disabled on the thread (0xffffaf8602c90080) because of Sync IO Wait.

    Process                       Thread           CID       UserTime KernelTime ContextSwitches Wait Reason         Time State
    reducted_executable_name.exe (ffffaf85feb300c0) ffffaf8602c90080 e88.2b24   57s.703    24s.281          549327 Executive   3h:25:43.718 Waiting
    
    Irp List:
        IRP              File   Driver Owning Process
        ffffaf8600e76640 (null) Npfs   reducted_executable_name.exe
    
    # Child-SP         Return           Call Site
    0 ffffd005e29d4570 fffff8025d7071d7 nt!KiSwapContext+0x76
    1 ffffd005e29d46b0 fffff8025d706d49 nt!KiSwapThread+0x297
    2 ffffd005e29d4770 fffff8025d705ad0 nt!KiCommitThreadWait+0x549
    3 ffffd005e29d4810 fffff8025dca1548 nt!KeWaitForSingleObject+0x520
    4 (Inline)         ---------------- nt!IopWaitForSynchronousIo+0x3e
    5 ffffd005e29d48e0 fffff8025dc9ffc8 nt!IopSynchronousServiceTail+0x258
    6 ffffd005e29d4990 fffff8025d877cc5 nt!NtReadFile+0x688
    7 ffffd005e29d4a90 00007fff4e820094 nt!KiSystemServiceCopyEnd+0x25
    8 000000002de1fbe8 00007fff4a9aa747 ntdll!ZwReadFile+0x14
    9 000000002de1fbf0 000000000047337e KERNELBASE!ReadFile+0x77
    a 000000002de1fc70 000000000000056c reducted_executable_name+0x7337e
    b 000000002de1fc78 000000c000573ec0 0x56c
    c 000000002de1fc80 0000000000008000 0xc000573ec0
    d 000000002de1fc88 000000c001701d54 0x8000
    e 000000002de1fc90 0000000000000000 0xc001701d54
    
    Irp Details: ffffaf8600e76640
        Thread           Process    Frame Count
        =========================== ===========
        ffffaf8602c90080 reducted_executable_name.exe           2
    Irp Stack Frame(s)
          # Driver           Major Minor Dispatch Routine Flg Ctrl Status  Device           File            
        === ================ ===== ===== ================ === ==== ======= ================ ================
        ->2 \FileSystem\Npfs READ      0 IRP_MJ_READ        0    1 Pending ffffaf85f7da2c00 ffffaf86107074b0
    
    ==============================================================
    ffffaf86107074b0 
    Related File Object: 0xffffaf8602a1f6a0
    
    Device Object: 0xffffaf85f7da2c00   \FileSystem\Npfs
    Vpb is NULL
    Flags:  0x40082
      Synchronous IO
      Named Pipe
      Handle Created
    File Object is currently busy and has 0 waiters.
    
    Process                       Thread           CID       UserTime KernelTime ContextSwitches Wait Reason         Time State
    reducted_executable_name.exe (ffffaf85feb300c0) ffffaf8602d06080 e88.2840   53s.969    24s.203          539612 Executive   3h:27:07.468 Waiting
    
    # Child-SP         Return           Call Site
    0 ffffd005e2b02630 fffff8025d7071d7 nt!KiSwapContext+0x76
    1 ffffd005e2b02770 fffff8025d706d49 nt!KiSwapThread+0x297
    2 ffffd005e2b02830 fffff8025d705ad0 nt!KiCommitThreadWait+0x549
    3 ffffd005e2b028d0 fffff8025dd06e87 nt!KeWaitForSingleObject+0x520
    4 ffffd005e2b029a0 fffff8025dd6b377 nt!IopCancelIrpsInThreadList+0x11f
    5 ffffd005e2b029f0 fffff8025dd06cd2 nt!IopCancelIrpsInThreadListForCurrentProcess+0xc3
    6 ffffd005e2b02ab0 fffff8025d877cc5 nt!NtCancelIoFileEx+0xc2
    7 ffffd005e2b02b00 00007fff4e8211c4 nt!KiSystemServiceCopyEnd+0x25
    8 000000002e01fc28 00007fff4a9f9ef0 ntdll!ZwCancelIoFileEx+0x14
    9 000000002e01fc30 000000000047337e KERNELBASE!CancelIoEx+0x10
    a 000000002e01fc70 000000002e01fc88 reducted_executable_name+0x7337e
    
    0xffffaf86`11746570 
    \Endpoint
    Device Object: 0xffffaf85f7db0b20   \Driver\AFD
    Vpb is NULL
    
    Flags:  0x6040400
      Queue Irps to Thread
      Handle Created
      Skip Completion Port Queueing On Success
      Skip Set Of File Object Event On Completion
    
  15. changed the title [-]os: TestPipeIOCloseRace timeout on Windows blocked in `syscall.CancelIoEx`[/-] [+]os: File.Close can hang when used with non-overlapped pipes on Windows[/+] on Sep 20, 2026
  16. qmuntal commented on Sep 21, 2026

    @qmuntal
    Member

    I've sent CL 835865, which fixes the hang occasionally reproduced by TestPipeIOCloseRace, which is the same as the the first hang described by @wiresock in https://www.ntkernel.com/a-rare-cancelioex-hang-in-go-on-windows/.

    @wiresock also mentions a hang involving sync pipes and async sockets. I'm still investigating that.

  17. gopherbot commented on Sep 21, 2026

    @gopherbot
    ContributorAuthor

    Change https://go.dev/cl/835865 mentions this issue: internal/poll: prevent thread reuse during Windows pipe cancellation

  18. gopherbot commented on Sep 22, 2026

    @gopherbot
    ContributorAuthor

    Change https://go.dev/cl/836565 mentions this issue: internal/poll, runtime: isolate synchronous pipe I/O on Windows

  19. qmuntal commented on Sep 22, 2026

    @qmuntal
    Member

    Ok, I think I got all the cases handled in CL 835865: poll.Fd now synchronizes CancelIoEx calls with read/write operations, and all synchronous I/O is done in dedicated worker threads that can't have any outstanding APC from previous async I/O that could block CancelIoEx calls.

  20. gopherbot commented on Oct 16, 2026

    @gopherbot
    ContributorAuthor

    Change https://go.dev/cl/850110 mentions this issue: Revert "internal/poll, runtime: isolate synchronous pipe I/O on Windows"

  21. gopherbot commented on Oct 17, 2026

    @gopherbot
    ContributorAuthor

    Change https://go.dev/cl/850227 mentions this issue: internal/poll, runtime: restore synchronous pipe I/O isolation on Windows

  22. moved this from Active to Done in Test Flakeson Oct 19, 2026
  23. added a commit that references this issue on Oct 19, 2026
    cb8219a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.OS-Windows

Type

No type

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions