Skip to content

feat(libkernel_sys): notify aio completions by signal or kevent and queue aio on sockets - #21463

Merged
oneandonlydean merged 15 commits into
boykopovar:mainfrom
frankea:feat/aio-sigevent-completion
Nov 25, 2026
Merged

oneandonlydean merged 15 commits into
boykopovar:mainfrom
frankea:feat/aio-sigevent-completion

Conversation

@frankea

@frankea frankea commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What

aio_read, aio_write and aio_fsync no longer throw for SIGEV_SIGNAL, SIGEV_THREAD_ID or SIGEV_KEVENT completion, or for a request on a socket. These were the two NotImplemented_nid_no_patch calls left in the shared Queue() helper of core/libs/prx/libkernel_sys/Aio.cpp. The behaviour follows FreeBSD 11.4: sys/kern/vfs_aio.c and sys/kern/sys_socket.c, with the kqueue parts checked against sys/kern/kern_event.c.

#19463 is merged into main (2026-11-21), and this branch has merged main at ef7dc4452df. It reuses the queued-signal entries that #19463 added to Signals.cpp (code, value, si_value at offset 32) instead of adding a second mechanism. The commits of this PR are 613be0a396a, 660296545c1, 4c721b9c105, 4c9710db5a6, ada4cc96312, d300f12e04e, 82fcbf5e84d and 908178b6689, plus merges of main.

SIGEV_KEVENT (vfs_aio.c aio_aqueue L1589-L1605, filt_aioattach/filt_aio L2492-L2539, aio_free_entry L532, aqueue_fail L1645-L1650):

  • sigev_notify_kevent_flags (the low 16 bits of the sigevent union) other than EV_CLEAR, EV_DISPATCH and EV_ONESHOT fail with EINVAL, after kernelinfo is stored, as aio_aqueue checks them there.
  • sigev_notify_kqueue (sigev_signo) that is not a kqueue fails with EBADF, as kqueue_acquire (L1496) answers, and the error is stored in the aiocb.
  • The knote has ident = the aiocb address, filter EVFILT_AIO, udata = sigev_value, and the requested flags without EV_FLAG1, which filt_aioattach clears.
  • At completion (also by aio_cancel) it fires with EV_EOF and data = the request's error (0, ECANCELED, an errno), as filt_aio sets them. The knote keeps that error, so a re-activated knote (an EV_CLEAR one after a later change) reports it again, as filt_aio sets kn_data on every call. It stays level-triggered until aio_return or aio_waitcomplete frees the request, which deletes the knote as aio_free_entry does through knlist_delete.
  • A request that fails after registration (a pipe, EOPNOTSUPP) deletes its knote, as aqueue_fail does.
  • A new request on an aiocb address that still has an EVFILT_AIO knote in that kqueue (the earlier request finished but was not yet returned) replaces that knote with a fresh one bound to the new request (908178b6689). The earlier request's completion and aio_return then no longer touch it, and the new request's completion and aio_return fire and free it. Before, the old knote kept the old request's token, so it re-reported the old completion at once, the new completion did not fire it, and aio_return of the old request deleted it.
  • Kqueue.cpp: a user EV_ADD of a new EVFILT_AIO knote still fails with EPERM (user EV_FLAG1 is stripped by kqueue_kevent L1087, then filt_aioattach refuses). A change to an existing aio knote now takes the generic path, as kqueue_register (L1234-L1493) does: EV_DELETE, EV_ENABLE/EV_DISABLE, EV_FORCEONESHOT and a new udata. A finished knote is re-activated by such a change, as kqueue_register calls f_event again at done_ev_add.
  • New libkernel helpers KqueueAddAio_nid_no_patch, KqueueAioDone_nid_no_patch and KqueueAioFree_nid_no_patch in Kqueue.cpp, declared in libkernel/include/Api.hpp.

SIGEV_SIGNAL and SIGEV_THREAD_ID (vfs_aio.c aio_sendsig L469-L485, aio_bio_done_notify L874-L940):

  • The completion posts sigev_signo with si_code SI_ASYNCIO (0x10004), si_value = sigev_value and si_pid 0, as ksiginfo_set_sigev and aio_sendsig fill it.
  • SIGEV_THREAD_ID targets sigev_notify_thread_id; an unknown thread sends nothing, as sigev_findtd returns ESRCH and the completion goes on.
  • New SendValueSignal_nid_no_patch in Signals.cpp follows feat(libkernel): deliver SIGEV_SIGNAL and SIGEV_THREAD_ID ktimer expiries #19463's SendTimerSignal without the overrun accounting: an ignored signal is dropped, a signal the target blocks is queued (each completion queues its own entry, as KSI_INS does), and the mask is checked again after queueing.
  • aio_return and aio_waitcomplete remove the request's own completion signal if it is still queued, as aio_free_entry (L534) calls sigqueue_take(&job->ksi). Each queued entry carries a ticket, so a request removes only its own entry, not one of another request with the same sigev_value.
  • Same gap as feat(libkernel): deliver SIGEV_SIGNAL and SIGEV_THREAD_ID ktimer expiries #19463: a target thread that does not block the signal throws (NotImplemented_nid_no_patch), because guest handlers do not run on the aio threads. For SIGEV_SIGNAL the target is the submitting thread, where FreeBSD posts to the process; this matches how feat(libkernel): deliver SIGEV_SIGNAL and SIGEV_THREAD_ID ktimer expiries #19463 picks the arming thread.

Sockets (sys_socket.c soo_aio_queue L774-L808, soaio_process_job L560-L673, soo_aio_cancel L743-L771):

  • aio_fsync and a negative offset on a socket fail with EINVAL, as aio_aqueue does for a file without a vnode. The socket type no longer counts as a vnode for that check.
  • Requests run in submission order per socket and direction on their own thread, which waits until the socket is readable or writable and then calls recv or send with MSG_DONTWAIT (MSG_NBIO), and MSG_NOSIGNAL on sends.
  • A read completes with what was read, 0 at end of file. A write that would block is put back at the head of the queue when nothing was sent or the socket is blocking, and completes with the bytes sent when the socket is non-blocking. EINTR or EWOULDBLOCK after progress completes with the progress.
  • EPIPE on a write without SO_NOSIGPIPE posts SIGPIPE with SI_KERNEL, as soaio_process_job (L620-L624) calls kern_psignal(job->userproc, SIGPIPE), through the same helper. That is process-directed, so like SIGEV_SIGNAL it targets the submitting thread, also when the request uses SIGEV_THREAD_ID for its completion.
  • aio_cancel on a waiting socket request completes it with ECANCELED (AIO_CANCELED), or with the bytes already sent and AIO_NOTCANCELED when part was sent, as soo_aio_cancel and aio_cancel_job (L576-L624) count it.
  • aio_cancel on a socket request in the middle of an attempt gives AIO_NOTCANCELED and marks it, as aio_cancel_job sets KAIOCB_CANCELLED on a job without a cancel function. When that attempt would put the request back, it completes instead: with the bytes already moved, or ECANCELED when none moved, as soaio_process_job (L651-L660) does when aio_set_cancel_function fails.

The libkernel_sys debt entry is rewritten gap first (951 characters): the signal throw, the submitting-thread target, the 10 ms socket poll and the host send that can block (below). It drops the claim that a bad aio_suspend pointer crashes the host, which is no longer true on main (aio_suspend copies its list and timeout in with GuestCopyIn and returns EFAULT).

Progress (python3 tools/progress.py --module libkernel_sys, main at fb233c9): main 193/820, this branch 195/820. aio_read, aio_write and aio_fsync become implemented. aio_cancel becomes pending in the count: a cancelled request with SIGEV_SIGNAL now reaches the unblocked-signal throw through its completion, so the scanner sees that throw from aio_cancel. Before this PR such a request could not be created, since aio_read threw. libkernel goes from 716 to 717 through #19463 only.

Tested

macOS 27.0.1 on Apple silicon (arm64), Release build with Ninja and AppleClang.

  • 2026-11-21, head 19980cb26f4 (merge of main ef7dc4452df), x86_64 build: guest_kernel_sys_aio passed 10 of 10; guest_kernel_sys_ktimer, guest_kernel_sys_ktimer_exit_armed, guest_kernel_sys_ktimer_exit_deleted, guest_legacy_signal_mask and guest_kqueue passed. guest_kqueue_cleared_race passed when run directly, in 57 s on a host at load average about 180, which is over its 30 s ctest limit; it does not involve aio. With the 908178b6689 change to Kqueue.cpp reverted, guest_kernel_sys_aio fails at the first check after the second request on the reused aiocb.
  • 2026-11-18, head 82fcbf5e84d: guest_kernel_sys_aio passed 10 of 10 on Windows 11 (RTX 4090 box, MinGW build) and 3 of 3 on macOS.

Earlier runs:

  • guest_kernel_sys_aio passed 10 of 10 consecutive runs, about 0.54 s each, after merging main fb233c9.
  • ctest -R over guest_kernel_sys_aio, guest_kernel_sys_ktimer, guest_kernel_sys_ktimer_exit_armed, guest_kernel_sys_ktimer_exit_deleted, guest_signals, guest_signal_interrupt, guest_signal_handler_mask, guest_sigtimedwait, guest_kernel_sig_pending, guest_signal_context, guest_equeue_events, guest_kqueue and guest_kqueue_cleared_race: 13 of 13 passed. public_headers and its compile tests: 65 of 65 passed.
  • With the main Aio.cpp and the new test, the test stops with aio completion delivering a signal or a kevent not implemented.

New test cases in core/libs/tests/GuestKernelSysAio.cpp:

  • Kevent: the event's ident, filter, flags (EV_EOF), data and udata; level-triggered until aio_return, then gone (EV_DELETE gives ENOENT); a second request on the same aiocb before the first is returned reports nothing while pending, nothing after aio_return of the first, then fires once with its own udata and is gone after its own aio_return; EV_ONESHOT and EV_CLEAR report once; a later EV_ADD change re-reports a finished EV_CLEAR knote with the new udata; a cancelled request fires with data ECANCELED, and a cancelled EV_CLEAR request re-reported by a later change still has data ECANCELED; a user EV_DELETE before completion means no event; a forged EV_ADD of EVFILT_AIO still gives EPERM; EBADF for a descriptor that is not a kqueue and EINVAL for a bad flag, both stored in the aiocb; a pipe request leaves no knote.
  • Signals: SIGUSR1 blocked, sigtimedwait returns SI_ASYNCIO, si_pid 0 and the value; two completions queue two entries in order; SIGEV_THREAD_ID to the calling thread; an unknown thread id sends nothing; an ignored SIGURG is dropped; a cancelled request still signals; aio_return and aio_waitcomplete leave no SIGUSR1 pending (sigpending, sigtimedwait gives EAGAIN); two requests with the same sigev_value: after sigtimedwait takes the first one's signal, aio_return of the first leaves the second one's signal queued.
  • Sockets (AF_UNIX stream pair): aio_fsync and a negative offset give EINVAL; a waiting read is cancelled; two queued reads complete in order from one write; a short read completes with 2 bytes; a write with SIGEV_KEVENT; end of file reads 0; EPIPE with SIGPIPE ignored; a 1 MiB write on a blocking socket gives AIO_NOTCANCELED and completes once drained; on a non-blocking socket it completes with part of the bytes; a read cancelled in the middle of an attempt (held there by a test hook, AioHoldSocketForTest_nid_no_patch) gives AIO_NOTCANCELED twice, and after the test drains the data first the request completes with ECANCELED instead of waiting again; SIGPIPE from a write with SIGEV_THREAD_ID to another thread (which blocks the completion signal but not SIGPIPE) is queued for the submitting thread, which blocks it.

Mutation check, 10 hand mutations: 8 failed the test (SIGEV_THREAD_ID treated as process-directed, the knote not freed by aio_return, the knote not freed after EOPNOTSUPP, no signal removal in aio_return, removal of any aio entry instead of the request's own, no cancelled check at the requeue (the request never completes), a re-activated knote without its error, SIGPIPE to the SIGEV_THREAD_ID thread). 2 survived on macOS: completing a blocking socket write early, and cancelling a partly sent write as ECANCELED. The macOS host blocks in send(..., MSG_DONTWAIT) on a blocking AF_UNIX stream socket when the data does not fit (a standalone C program confirmed it), so a partly sent blocking write never happens there. Linux honours MSG_DONTWAIT, so these paths need a Linux run. On Windows MSG_DONTWAIT is a poll followed by a blocking send in WaitForTransfer; the debt entry records both hosts.

$ python3 tools/check_conventions.py --base origin/main
All conventions checks passed.

Overlap. python3 tools/pr_overlap.py --names aio_read aio_write aio_fsync and gh pr list --search for each name, SIGEV_KEVENT, EVFILT_AIO and sigevent find no open PR that implements aio notification or socket aio. #16191 changes the same Queue() function; git merge-tree merges it with this branch without conflicts. #20808 changes the same libkernel_sys debt entry in its own fragment (docs-kernel-sys-aio-suspend-debt.md) to replace the stale aio_suspend crash sentence with the EFAULT behaviour. The two texts agree: this one drops the sentence. The files merge without conflicts, but tools/debt_fold.py --check refuses two fragments that change the same entry, so whichever lands second folds the other's fragment into its own; this fragment applies cleanly on top of #20808's folded entry (checked with debt_fold.py locally). #9389 (sigqueue) also changes Signals.cpp and is not needed here.

Not verified:

  • the console
  • a Linux run of the partial-write socket paths on the current head (a reviewer ran the suite on Linux at 22ee655388)
  • delivery to a thread that does not block the signal, which still throws

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none (feat(libkernel): deliver SIGEV_SIGNAL and SIGEV_THREAD_ID ktimer expiries #19463 is merged)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

…nish cancelled socket requests

aio_return and aio_waitcomplete remove the request's own queued SI_ASYNCIO entry by ticket, as aio_free_entry calls sigqueue_take. A cancel that reaches a socket request mid-attempt marks it, and the requeue completes it with the bytes moved or ECANCELED, as soaio_process_job does when aio_set_cancel_function fails. A re-triggered EVFILT_AIO knote reports the request's error again, as filt_aio sets kn_data. SIGPIPE from a socket write targets the submitting thread rather than the SIGEV_THREAD_ID one. The debt entry drops the stale aio_suspend pointer claim.

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 22ee655388:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_kernel_sys_aio_tests, guest_kernel_sys_ktimer_exit_tests, guest_kernel_sys_ktimer_tests built cleanly.
  • CTest (guest_kernel_sys_ktimer, guest_kernel_sys_ktimer_exit_armed, guest_kernel_sys_ktimer_exit_deleted, guest_kernel_sys_aio):
    1/4 Test #929: guest_kernel_sys_ktimer_exit_armed .....   Passed    0.03 sec
    2/4 Test #930: guest_kernel_sys_ktimer_exit_deleted ...   Passed    0.08 sec
    3/4 Test #933: guest_kernel_sys_aio ...................   Passed    0.30 sec
    4/4 Test #928: guest_kernel_sys_ktimer ................   Passed    0.63 sec
    100% tests passed, 0 tests failed out of 4
    
  • Negative control: with core/libs/prx/libkernel/Equeue/src/Kqueue.cpp, core/libs/prx/libkernel/System/src/Signals.cpp, core/libs/prx/libkernel/Time/Ktimer.cpp, core/libs/prx/libkernel/include/Api.hpp, core/libs/prx/libkernel_sys/Aio.cpp reverted to main, the new tests do not build/link without the change; restoring it makes them build and pass.
  • Code reading:
    • Verified EVFILT_AIO knote registration, modification, retriggering, completion (EV_EOF and error propagation), and cleanup in core/libs/prx/libkernel/Equeue/src/Kqueue.cpp against FreeBSD 11.4 vfs_aio.c and kern_event.c.
    • Verified GuestSiginfo layout static assertions (sizeof == 80, value at offset 32, timerid at offset 40, overrun at offset 44) and queued signal handling in core/libs/prx/libkernel/System/src/Signals.cpp.
    • Verified thread-directed signal registration (RegisterSignalThread) and lookup (SignalThread) synchronization and safety across sigwait/sigtimedwait/sigsuspend paths.
    • Verified ktimer_getoverrun_nid_postfix locking and overrun retrieval via TimerSignalOverrun in core/libs/prx/libkernel/Time/Ktimer.cpp.
    • Verified CMake test target definitions and Windows/Linux portability in core/libs/CMakeLists.txt.

Looks Good To Me

@MarcZX10 MarcZX10 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.

Reviewed — changes requested

Changes are required before merge: remove the dangling thread registry entries and make the socket worker lifetime safe when its queue is removed.

What I ran

Reviewed head 22ee65538880b0d881102b7857b503b2a8f0d8fc; no merged preview or programmatic checks were run. Inspected the prepared diff and repository context with repo_read.py.

Results

Check Result Note
Diff review passed Prepared change inspected
Build and tests not run No local execution available
Thread and socket lifetime failed Two concrete lifetime defects found

Findings

Blocking

  • core/libs/prx/libkernel/System/src/Signals.cpp:150: RegisterSignalThread stores a raw ThreadSignals* in the global map, and no corresponding unregister or erase path exists. After a guest thread exits, a later timer or AIO completion can find that stale pointer and call SignalBlocked through it. This is a use-after-lifetime risk on thread exit. Remove registry entries as threads exit, or use storage whose lifetime safely outlives all senders.
  • core/libs/prx/libkernel_sys/Aio.cpp:257: SocketWorker erases its SocketQueue node once the job deque becomes empty. The worker drops aio.lock while polling at lines 251–254; meanwhile, another thread can enqueue on that same queue or cancel its last job, allowing the worker to erase the node after it was reused. The worker then holds an invalid list iterator/reference, causing undefined behavior. Keep queue nodes alive until the worker has reacquired the lock and confirmed they remain empty, coordinating enqueue/cancel with that lifecycle.

Non-blocking

None.

Sources

  • Changed code: core/libs/prx/libkernel/System/src/Signals.cpp and core/libs/prx/libkernel_sys/Aio.cpp.
  • Prepared diff and manifest; repository context read at the pinned head.

Not verified

  • Build, tests, console behavior, Linux behavior, and Windows behavior were not run in this review. The author reports macOS tests in the PR description; those were not independently run.
  • Read full changed text for core/libs/prx/libkernel/Equeue/src/Kqueue.cpp, core/libs/prx/libkernel/System/src/Signals.cpp, and core/libs/prx/libkernel_sys/Aio.cpp. Inspected changed hunks for the remaining files; did not read their full text. The manifest marks all listed changed files as included; files.json was not available through the reader.

To get this to a good state

Fix the thread registry and socket queue lifetimes, then rerun the relevant build and tests on the new head.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 25645 core/libs/prx/libkernel/Equeue/src/Kqueue.cpp L519-520
PR 27140 core/libs/prx/libkernel/System/src/Signals.cpp L457-466

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 7121 core/libs/prx/libkernel/Equeue/src/Kqueue.cpp
PR 9389 core/libs/prx/libkernel/System/src/Signals.cpp
PR 11215 core/libs/prx/libkernel/include/Api.hpp
PR 12682 core/libs/prx/libkernel/System/src/Signals.cpp
PR 12688 core/libs/prx/libkernel/System/src/Signals.cpp
PR 12700 core/libs/prx/libkernel/System/src/Signals.cpp
PR 12965 core/libs/prx/libkernel/System/src/Signals.cpp
PR 18190 core/libs/prx/libkernel/Equeue/src/Kqueue.cpp
core/libs/prx/libkernel/System/src/Signals.cpp
core/libs/prx/libkernel_sys/Aio.cpp

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Progress report (e57e2b9 → 7ddbf60)

📈 System libraries: 45.58% (+0.0051%, +3 implemented, -1 reverted functions)

✅ 3 implemented
Library Name
libkernel_sys aio_fsync_nid_postfix
libkernel_sys aio_read_nid_postfix
libkernel_sys aio_write_nid_postfix
⚠️ 1 went back to stubs
Library Name
libkernel_sys aio_cancel_nid_postfix

Changed libraries (implemented exports)

Library Before After Change
libkernel_sys 201/802 (25.06%) 203/802 (25.31%) +0.25%

frankea and others added 4 commits November 16, 2026 20:29
…l aio write

The partial-write case filled the socket buffer and then drained only
64 KiB, so on Linux the queued aio_write never got POLLOUT and
aio_cancel rightly returned AIO_CANCELED. Drain exactly the bytes the
fill loop wrote.
@oneandonlydean

Copy link
Copy Markdown
Collaborator

@frankea I pushed a test fix on top of your head (d300f12). In SocketPartialWrites the socket was filled and then only 64 KiB was drained, so on Linux the queued aio_write never saw POLLOUT, nothing was sent, and aio_cancel correctly returned AIO_CANCELED. The test now drains exactly the bytes the fill loop wrote. It passed 10 of 10 runs locally on Linux; Windows needs the new CI run.

@MarcZX10 I read your two points against this head:

  • RegisterSignalThread keeps ThreadSignals* forever, but those objects are never freed and guest thread ids come from a monotonic counter, so a stale entry cannot alias a new thread. It is a small per-thread leak, not a use after free.
  • In SocketWorker, the jobs.empty() check and aio.sockets.erase(queue) run in the same section under aio.lock, and QueueSocket and cancel touch the list under the same lock. Only the owning worker erases its node, so the iterator stays valid.

I do not see a change needed for either, unless you have a sequence that breaks it.

@MarcZX10 MarcZX10 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.

Reviewed — looks good

Nothing blocks this change based on the source and test coverage reviewed; the reported test runs were supplied by the author and were not run here.

What I ran

Reviewed head d300f12e04e452d404f46a9ee7eb1751ef649861. No commands or tests were run; the prepared diff and repository reader were the available review inputs.

Results

Check Result Note
Runtime code review passed AIO, signal, timer, and kqueue paths inspected
Test execution not run Test results are author-reported
Excluded changed file not applicable Deleted debt fragment adds no text

Findings

Blocking

None.

Non-blocking

None.

Not verified

The full changed-file texts were included for 10 of 11 changed files. The deleted docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.md was excluded because it has no added lines. I read targeted runtime ranges and test sections; I did not read every line of every included changed file. Linux, Windows, and console behavior were not run or confirmed here. The test outcomes in the PR description are author-reported.

To get this to a good state

Nothing is required.

@frankea

frankea commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for d300f12. The Windows job still failed on it, at the aio_error == EINPROGRESS check after the drain, so I ran the test on Windows 11 (RTX 4090 box, MinGW build) to see why. With a diagnostic print: the fill loop stopped at 2,097,152 bytes, and a blocking aio_write of 9,437,184 bytes on that socket completed in full (aio_error 0, aio_return 9,437,184) before anything read the other end. A non-blocking 9 MiB write also completed in full. So on a Windows host the whole write goes through at once, and neither "still in progress" nor "partial" can hold there.
82fcbf5 keeps your exact drain and changes two things: the blocking request is 4 × filled + 1 MiB, so it cannot fit in one buffer's worth where the host does limit it, and if the request has already completed after the drain the test requires a full aio_return instead of the cancel path. The non-blocking case uses the same size and accepts a full write only under _WIN32. The aio debt entry now says a macOS or Windows host may send a whole write at once, even if cancelled or non-blocking.
guest_kernel_sys_aio passes 10 of 10 on that Windows box and 3 of 3 on macOS (M5 Max, x86_64 build). I have not run it on Linux; your drain is unchanged, and the larger request only keeps the write pending longer there.
AI-assisted: yes (Claude Code)

@MarcZX10 MarcZX10 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.

Reviewed — comments

The review is incomplete because the full changed-line inventory and targeted source audit were not completed, so approval or a formal change request is not justified.

What I ran

Read the prepared description, commits, manifest, diff excerpt, and changed source excerpts through the pinned-head reader. No build or tests were run; author-reported results were not independently verified.

Results

Check Result Note
Source review not run Full changed-file inventory not read
Tests not run No commands executed

Findings

Blocking

None verified from the inspected excerpts.

Non-blocking

None.

Not verified

The full diff and remaining changed-file lines were not read, including most of Aio.cpp, the remaining signal helpers, tests, and build/debt changes. Thus correctness, test coverage, and the claims in the PR description remain unverified. Files listed as changed and included in the review folder: core/libs/CMakeLists.txt, core/libs/prx/libkernel/Equeue/src/Kqueue.cpp, core/libs/prx/libkernel/System/include/TimerSignals.hpp, core/libs/prx/libkernel/System/src/Signals.cpp, core/libs/prx/libkernel/Time/Ktimer.cpp, core/libs/prx/libkernel/include/Api.hpp, core/libs/prx/libkernel_sys/Aio.cpp, core/libs/tests/GuestKernelSysAio.cpp, core/libs/tests/GuestKernelSysKtimer.cpp, core/libs/tests/GuestKernelSysKtimerExit.cpp, docs/dev/debt/changes/feat-aio-sigevent-completion.md, and docs/dev/debt/changes/feat-libkernel-ktimer-signal.md. docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.md is deleted and has no new text to inspect.

To get this to a good state

Nothing is required.

@ycbuzi

ycbuzi commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tested 82fcbf5e84 merged into main, with the whole ctest suite on each machine below. Nothing fails that does not also fail on main on the same machine.

  • Windows Server 2022 (GitHub-hosted runner), full build, WinLibs GCC 15.2.0: 99% tests passed, 3 tests failed out of 6258; 99% tests passed, 4 tests failed out of 6258. 4 of the failing tests fail on main too. run
  • Windows Server 2025 (GitHub-hosted runner), full build, WinLibs GCC 15.2.0: 99% tests passed, 1 tests failed out of 6258; 99% tests passed, 1 tests failed out of 6258. 1 of the failing tests fail on main too. run

AI-assisted: yes (Claude Code); the runs are automated, this summary was written from their reports.

@frankea

frankea commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

The last red Windows job on 82fcbf5 is not the AIO test. In run 44372366544 every test passes except guest_sce_net (1 of 5211), which aborts at the stdio select check (line 3188 there, which required select on descriptors 0-2 to report exactly stdout and stderr ready). That run merged the PR into main 6286d36, which predates #23167 ("test(net): accept variable stdio readiness", b73dd77), the fix for exactly this check when Windows CI redirects the standard streams to pipes. This PR does not touch libSceNet or the stdio select path.
I merged current main (c8f72e9, includes #23167) into the branch with no conflicts and pushed it so CI reruns on a tree that has the fix. On the Mac build of the merged head, guest_kernel_sys_aio, guest_kernel_sys_ktimer, guest_kernel_sys_ktimer_exit, guest_kqueue and guest_legacy_signal_mask pass. Under a very heavily loaded host (load average about 200) the existing TimedWaits upper bound (< 200 ms for twenty 1 ms waits) tripped 2 times in 40 runs; a main build trips the same check 1 time in 40 on the same machine, so that is a pre-existing host-load sensitivity, not something this PR changes.
Thanks for the Windows Server 2022/2025 runs; they match this: nothing fails there that does not also fail on main.
AI-assisted: yes (Claude Code)

@MarcZX10 MarcZX10 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.

Reviewed — changes requested

Changes are required before merge: prevent an existing AIO knote from being rebound to a different request.

What I ran

Reviewed head 6822e196629f93825dfdfe93e63659a5cbae7dde using the prepared review artifacts and repo_read.py; no tests or build commands were run.

Results

Check Result Note
Diff and description passed Prepared artifacts reviewed
Targeted code review failed Found a knote reuse defect
Tests not run Author-reported results were not rerun

Findings

Blocking

  • core/libs/prx/libkernel/Equeue/src/Kqueue.cpp:735: When a new AIO request uses an ident that already has an EVFILT_AIO knote, this path updates the existing knote but leaves its AioNote::token unchanged. AIO completion and cleanup only act when that token matches the request (Kqueue.cpp:755-763, 767-773). Reusing an aiocb address can therefore leave the new request without its completion event and leave the old knote behind after aio_return. Reject the duplicate registration or safely replace/rebind the note so completion and cleanup match the new request.

Non-blocking

None.

Not verified

No tests or build were run. Full changed-file texts read: core/libs/prx/libkernel/Equeue/src/Kqueue.cpp and core/libs/prx/libkernel_sys/Aio.cpp. The prepared description, commits, manifest, and diff were read; other changed-file texts were not read. docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.md is deleted and has no new text. Author-reported test results were not independently verified.

To get this to a good state

Fix duplicate AIO knote registration so a request cannot inherit a knote with another request's token, then rerun the AIO tests.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 21, 2026
@frankea

frankea commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

The duplicate-knote point is right: a second request on an aiocb whose earlier request had finished but not been returned kept the old AioNote token, so the knote re-reported the old completion at once, the new completion never fired it, and aio_return of the old request deleted it out from under the new one. 908178b makes KqueueAddAio_nid_no_patch delete any existing EVFILT_AIO knote for that ident in the target kqueue and add a fresh one bound to the new request's token. The old request's completion and aio_return no longer match it; the new request's completion fires it and its aio_return frees it. A knote for the same aiocb on a different kqueue is untouched and still belongs to the old request. This follows the rebind option rather than FreeBSD, whose EVFILT_AIO keeps the existing knote bound to the old request when the same aiocb is resubmitted to the same kqueue, so the new request gets no event there; the console behaviour for this reuse is not measured.
KeventCompletion in GuestKernelSysAio.cpp now covers it: complete a request without returning it, resubmit the same aiocb with the worker held, then require no event while pending, no event after aio_return of the first request, one event with the new udata after the second completes, and no knote after the second aio_return. With the Kqueue.cpp hunk reverted the test fails at the first of those checks.
I also merged current main (ef7dc44, which now includes #19463), head 19980cb. On the Mac (x86_64 Release build) guest_kernel_sys_aio passed 10 of 10, and guest_kernel_sys_ktimer, both guest_kernel_sys_ktimer_exit cases, guest_legacy_signal_mask and guest_kqueue pass; check_conventions.py passes. The PR body now describes the rebind and the new test.
AI-assisted: yes (Claude Code)

@MarcZX10 MarcZX10 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.

Reviewed — changes requested

Changes are required before merge: prevent zero-byte socket requests from waiting indefinitely and preserve the pending-signal queue limit for AIO completions.

What I ran

Reviewed head 19980cb26f4fc7395f870a5cb9199ca84c446114 against main. Read the prepared description, commits, diff, manifest, all included changed files, and targeted socket, signal, and kqueue context through repo_read.py. No build or tests were run.

Results

Check Result Note
Changed-code review failed Two concrete edge cases found
Build and tests not run No commands run

Findings

Blocking

  • core/libs/prx/libkernel_sys/Aio.cpp:223: For a zero-byte socket read, recv returns 0 only when data is available or the peer has closed; while a live socket has no data, SocketWorker waits for POLLIN before it calls RunSocketJob. The queued request therefore never completes even though a zero-byte read should complete immediately. The write path has the same readiness gating. Complete zero-byte socket requests without waiting for socket readiness, and add a regression test.
  • core/libs/prx/libkernel/System/src/Signals.cpp:789: QueueValueSignal appends every AIO completion signal without enforcing MaxQueuedPerSignal (1024), unlike the existing MarkPending path. Repeated completions to a blocked signal can grow the queue without bound and bypass the established per-signal cap. Enforce the cap and define the completion behavior when it is reached; add a capacity test.

Non-blocking

None.

Not verified

No build, tests, Linux run, or console run was performed. The deleted debt fragment was excluded because it has no added lines. The code review covered the included changed files: Kqueue.cpp, Signals.cpp, Api.hpp, Aio.cpp, GuestKernelSysAio.cpp, and feat-aio-sigevent-completion.md.

To get this to a good state

Handle zero-byte socket requests without readiness polling and enforce the signal queue limit. Add regression coverage for both cases, then rerun the AIO test suite on the new head.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@MarcZX10 I looked at both points on 19980cb.

  1. Zero-byte socket aio waiting for readiness: FreeBSD's socket aio (soo_aio_queue / soaio_process_job) is also gated on soreadable/sowriteable regardless of nbytes, so a zero-byte read on an idle socket stays queued there too. aio_cancel still works on it here.
  2. The AIO signal path skipping MaxQueuedPerSignal: it is bounded another way. Each aio job holds at most one ticket, outstanding jobs are capped at QueuePerProcess = 256 (Aio.cpp:318), and aio_return takes the ticket back. FreeBSD likewise uses the job's preallocated ksiginfo, outside the per-process sigqueue limit.

So I don't see a defect in either. Could you take another look?

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 22, 2026

@MarcZX10 MarcZX10 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.

Reviewed — looks good

The reviewed changes implement AIO signal and kqueue completion notifications and socket requests; no verified blocking defect was found in the code read.

What I ran

Reviewed head 7ddbf60a2efb22c67bd96cfce1cd97703ffa6b86 against main. No commands or tests were run; the test results below are author-reported.

Results

Check Result Note
Code review passed Inspected the main AIO, signal, and kqueue paths
Tests not run Test runs are reported by the author
Console and Linux behavior not run Not verified on this head

Findings

Blocking

None.

Non-blocking

None.

Not verified

The console, Linux behavior for partial socket writes on this head, unblocked signal delivery, and the deleted debt fragment were not verified. The author reports macOS and Windows test runs and identifies the unblocked-signal path as still throwing. Files read: description.md, commits.md, manifest.json, diff.patch, Kqueue.cpp, Signals.cpp, Api.hpp (diff only), Aio.cpp, GuestKernelSysAio.cpp, and feat-aio-sigevent-completion.md. Excluded: deleted docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.md; files.json was unavailable in the review folder.

To get this to a good state

Nothing is required.

@Helldiverr

Copy link
Copy Markdown
Contributor

Windows run: on the merge, the seven aio, ktimer, signal-mask and kqueue tests pass three times. They also pass on main. With the four changed sources reverted, guest_kernel_sys_aio aborts on the NotImplemented throw. Of 11 mutations, 7 fail. The four survivors are all on the partial socket write path, which this host never takes. A local test for SO_NOSIGPIPE catches one mutation that nothing else does.

Existing runs.

  • frankea:
    • At 82fcbf5e84: 10 of 10 on Windows 11 and 3 of 3 on macOS.
    • At 19980cb26f: macOS only.
    • Ten hand mutations on macOS, of which 2 survived.
    • frankea's 11-18 comment found that a Windows host sends a whole 9 MiB write at once.
  • ycbuzi ran the whole suite on Windows Server 2022 at 82fcbf5e84, pass-only.
  • PrivacyOnion ran on Linux at 22ee655388.
  • oneandonlydean pushed the drain fix d300f12e04. On 19980cb26f they also answered MarcZX10's zero-byte read and MaxQueuedPerSignal points.

I found no Windows run at the head. The Kqueue.cpp knote change from 908178b6689 has had no Windows run.

What this run adds.

  • A first Windows run of the head, merged onto current main.
  • A negative control.
  • 11 mutations.
  • A local test for the SO_NOSIGPIPE branch.

Code.

  • The four surviving mutations are on paths that need a partial non-blocking send:

    • the requeue condition, Aio.cpp:239;
    • the partial-progress branch of CancelSocketJob, Aio.cpp:275;
    • the progress-then-EAGAIN rewrite, Aio.cpp:244;
    • the partial-write term of wouldBlock, Aio.cpp:229.

    The first two match the two macOS survivors in the body. Removing the rewrite at 244 would make a partial non-blocking write return -1. The non-blocking case still passed, so on this host the 4 × filled + 1 MiB write was accepted whole, as frankea's 11-18 comment measured. The debt entry records this. These paths still need a Linux run at the head.

  • KqueueAioDone (Kqueue.cpp:763) checks the token, but no test exercises that check. Turning it off passes. Hitting it would take an earlier request on the same aiocb address that completes after a later request has replaced its knote.

  • No test exercises the SO_NOSIGPIPE check at Aio.cpp:228. The existing EPIPE case ignores SIGPIPE, so it passes whether or not the signal is posted.

  • KqueueAioFree (Kqueue.cpp:776-781) checks the token in one EditEvent and deletes in a separate DeleteEvent. A KqueueAddAio on the same aiocb between the two would lose its fresh knote. Reaching that needs aio_return and a resubmission on one aiocb from two threads at once.

  • The debt fragment records that a SIGEV_SIGNAL completion and the socket SIGPIPE target the submitting thread, where FreeBSD posts to the process. It also records the throw for a target that does not block the signal.

PR body.

  • Tested lists Windows only at 82fcbf5e84. The knote replacement in 908178b6689 and the later merges of main are covered by macOS only.
  • The two macOS survivors in the mutation paragraph also survive here, along with two more on the same path.

Suggestion. I added this test locally only, to core/libs/tests/GuestKernelSysAio.cpp, with main() calling it after SigpipeToSubmitter(). 0xffff and 0x800 are SOL_SOCKET and SO_NOSIGPIPE.

void NoSigpipeSocket() {
    int pair[2] = {-1, -1};
    Require(socketpair_nid_postfix(AfUnix, SockStream, 0, pair) == 0);
    const int one = 1;
    Require(setsockopt_nid_postfix(pair[0], 0xffff, 0x800, &one, sizeof(one)) == 0);
    Require(close_nid_postfix(pair[1]) == 0);
    const auto pipeSet = SignalSet(Sigpipe);
    Require(pthread_sigmask_nid_postfix(SigBlock, &pipeSet, nullptr) == 0);
    char buffer[8] = {};
    auto broken = Request(pair[0], buffer, sizeof(buffer));
    Require(aio_write_nid_postfix(&broken) == 0);
    Wait(broken);
    Require(aio_return_nid_postfix(&broken) == -1 && Error() == Epipe);
    Require(!SignalPending(Sigpipe));
    Require(pthread_sigmask_nid_postfix(SigUnblock, &pipeSet, nullptr) == 0);
    Require(close_nid_postfix(pair[0]) == 0);
}

With it in place, line 893 is the !SignalPending(Sigpipe) check.

Negative control and mutations.

  • The negative control reverts Aio.cpp, Kqueue.cpp, Signals.cpp and Api.hpp to main and keeps the new test. It needs two stubs for the test hooks, AioHoldSocketForTest_nid_no_patch and AioSocketsHeldForTest_nid_no_patch, or it does not link.
  • Each mutation ran once on the merge, with the local test in place, over guest_kernel_sys_aio and guest_kqueue.
Change Result
Negative control guest_kernel_sys_aio aborts: aio completion delivering a signal or a kevent not implemented; guest_kqueue passes
Requeue drops || Blocking(job->descriptor) (Aio.cpp:239) passes
CancelSocketJob partial-progress branch disabled (Aio.cpp:275) passes
SIGPIPE sent without the !NoSigpipeSet check (Aio.cpp:228) fails at line 893, the local test only
SIGPIPE send removed (Aio.cpp:228) fails at line 821, SigpipeToSubmitter
EINTR/EAGAIN after progress no longer cleared (Aio.cpp:244) passes
sigev_notify_kevent_flags check removed (Aio.cpp:344) fails at line 578, bad flags
wouldBlock drops the partial-write term (Aio.cpp:229) passes
si_value not copied for SI_ASYNCIO (Signals.cpp:463) fails at line 633
KqueueAddAio keeps the old knote (Kqueue.cpp:747) fails at line 519, reused aiocb
KqueueAioDone ignores the token (Kqueue.cpp:763) passes
RetriggerAioKnote never re-arms (Kqueue.cpp:526) fails at line 542, re-reported EV_CLEAR knote

Tests.

test main merge 1 merge 2 merge 3
guest_kernel_sys_aio, guest_kernel_sys_ktimer, guest_kernel_sys_ktimer_exit_armed, guest_kernel_sys_ktimer_exit_deleted, guest_legacy_signal_mask, guest_kqueue, guest_kqueue_user_state 7/7 pass 7/7 pass 7/7 pass 7/7 pass
guest_kernel_sys_aio and guest_kqueue with the local test not run pass pass pass

On the merge, tools/check_conventions.py --base upstream/main passes with no findings, and tools/debt_fold.py --check exits 0.

  • CPU: Ryzen 9 9950X3D
  • OS: Windows 11 Pro 26300
  • Toolchain: WinLibs GCC 15.2, Release
  • Commits: head 7ddbf60a2e, merged onto main 61250ca018 as 05172fca2d

AI-assisted: yes

@oneandonlydean
oneandonlydean merged commit f7862ca into boykopovar:main Nov 25, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants