Skip to content

feat(libkernel): add pipe write events and socket low watermarks to sceKernelAdd*Event - #10645

Merged
oneandonlydean merged 10 commits into
boykopovar:mainfrom
rocklouis055:feat/equeue-pipe-write-lowat-on9099
Nov 26, 2026
Merged

oneandonlydean merged 10 commits into
boykopovar:mainfrom
rocklouis055:feat/equeue-pipe-write-lowat-on9099

Conversation

@rocklouis055

@rocklouis055 rocklouis055 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What

Builds on #9099 (@aarushkha's regular-file events, merged). It extends sceKernelAddReadEvent and sceKernelAddWriteEvent with the two cases kevent already handles and these still throw on:

  • Write end of a pipe: sceKernelAddWriteEvent takes it through GuestSockets::PipeWriteState, with EV_EOF once the read end closes and SCE_KERNEL_ERROR_EPIPE for a new event added after that, as AddDescriptorKnote in Kqueue.cpp does; adding an existing one again succeeds and replaces its udata, as kevent does. A read event on the write end and a write event on the read end still throw, as in kevent.

  • Socket low watermark: a size above 1 on a stream socket becomes the event's lowWater, as NOTE_LOWAT does in kevent (DescriptorLowWater); above 1 on a socket that is not a stream throws, as there. Adding the event again replaces the mark, as ModifyKnote does, and a size above INT64_MAX, which as kn_sdata would be a mark below 1, throws as DescriptorLowWater does. The size stays ignored on pipes, as in kevent, and a size above 1 on a regular file keeps feat(libkernel): answer sceKernelAddReadEvent and sceKernelAddWriteEvent on regular files #9099's throw.

  • Datagram size on Windows: GuestSockets::Ready reads a datagram socket's data from an overlapped MSG_PEEK receive, cancelled without waiting if it would pend (its OVERLAPPED, event and buffer stay in a never-freed pool until the kernel completes it), so it reports the next datagram's size as Linux and macOS do; Winsock's FIONREAD reports 1 for a zero-length datagram (traced by @ycbuzi).

The debt entries for these calls are updated: the pipe entry now covers both ends, the socket entry states the low watermark (still above the 1000-character warning it already triggers on main), and a new entry covers the Windows datagram size.

#9823 also edits these lines, replacing NotImplemented_nid_no_patch with throw; it does not add either case.

Order with overlapping PRs

#12296 has merged. The remaining overlap is with @Felipebmaitan's #12682 → #12688 → #12700 stack: both sides add an #include at the same place in Socket/src/Udp.cpp, and nothing else conflicts or calls the other side's code (composed and run on Linux and Windows by @B-Howell). Proposed: this PR first, then that stack, keeping both includes; if its author prefers the reverse, this PR will declare Depends on: #12700 and rebase. Asked here; not yet agreed.

Tested

Linux x86-64 (Ubuntu 26.04, GCC 15), Release, on bf70e27f7d (rebased on main ba8dcc6ae8). guest_socket_events covers: a pipe write event with EV_EOF, EPIPE for a new event after the read end closed and a successful re-add with new udata; stream read marks of 6 and INT64_MAX that time out at 3 bytes, a re-add from INT64_MAX to 1 that fires with data 3 and from 1 to 6 that times out again; a write mark of 64; and a connected loopback datagram socket with an empty queue (times out), a zero-length datagram (data 0), and a zero-length then a 3-byte datagram (data 0, then 3), and a sender and a racing reader on that socket while the read event is polled (every data 0 or 3, then each late datagram read until the event times out). guest_socket_submitted_records checks the peek pool: a submitted record is not handed out again before completion and is reused after it, and a failed event creation is retried on the next acquire. It, guest_equeue_events, guest_kqueue and guest_udp pass 20 times with ctest --repeat until-fail:20. Reverting the re-add mark update, or returning EPIPE on every re-add, makes guest_socket_events abort. The Windows Udp.cpp passes a syntax check with clang for x86_64-windows-gnu (no diagnostics in the new code), and @ycbuzi ran 8e19a7affc on Windows (the four tests pass; with only main's Udp.cpp the zero-length datagram check fails), and @B-Howell ran b1d851bf47 on Windows 11 and WSL2 (the seven socket and event tests pass 3 of 3; with main's Equeue.cpp and Udp.cpp, guest_socket_events aborts); @tkcm01 ran b1d851bf47 on macOS (Apple M4, x86_64 under Rosetta 2): guest_socket_events passes 30/30 and guest_socket_submitted_records 5/5, and with only this PR's tests guest_socket_events aborts on the missing low watermark. The pipe write-event cases are skipped there, since the pipe write state throws on macOS, as for kevent.

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
  • 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
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with 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 the exact head e673953786a79b3252b673438e45956daad61253. The added pipe-write path matches kevent handling for writable readiness, EV_EOF, and EPIPE after the read end closes; the low-watermark path uses the same stream-socket restriction and poll threshold as DescriptorLowWater. The added tests exercise both wrong pipe ends, closed-reader behavior, stream thresholds, and rejection on datagram sockets. The hosted conventions check passes, with the existing overlong debt-entry warning; the repository-local convention check reports the same warning and no errors. The PR correctly declares its dependency on #9099, which remains open. I did not independently run the product build.

@github-actions

github-actions Bot commented Oct 24, 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 18197 core/libs/prx/libkernel/Socket/src/Udp.cpp L52

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 4563 core/libs/prx/libkernel/CMakeLists.txt
PR 6149 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 6936 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 7121 docs/dev/debt/libkernel.md
PR 7149 docs/dev/debt/libkernel.md
PR 7447 docs/dev/debt/libkernel.md
PR 8605 core/libs/prx/libkernel/Socket/src/Udp.cpp
docs/dev/debt/libkernel.md
PR 9156 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 9293 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Equeue/Equeue.cpp
docs/dev/debt/libkernel.md
PR 9297 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Equeue/Equeue.cpp
docs/dev/debt/libkernel.md
PR 9302 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Equeue/Equeue.cpp
docs/dev/debt/libkernel.md
PR 9383 core/libs/prx/libkernel/CMakeLists.txt
PR 9389 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 9557 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 9566 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 9938 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 11215 docs/dev/debt/libkernel.md
PR 11661 docs/dev/debt/libkernel.md
PR 11689 docs/dev/debt/libkernel.md
PR 11698 docs/dev/debt/libkernel.md
PR 11896 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Socket/src/Udp.cpp
docs/dev/debt/libkernel.md
PR 12965 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Socket/src/Udp.cpp
PR 15037 docs/dev/debt/libkernel.md
PR 16790 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 18190 core/libs/prx/libkernel/CMakeLists.txt
core/libs/prx/libkernel/Socket/src/Udp.cpp
PR 19181 core/libs/prx/libkernel/CMakeLists.txt
PR 21022 core/libs/prx/libkernel/CMakeLists.txt
PR 21026 core/libs/prx/libkernel/CMakeLists.txt
PR 21041 core/libs/prx/libkernel/CMakeLists.txt
PR 21604 core/libs/prx/libkernel/CMakeLists.txt
PR 24322 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md
PR 24910 core/libs/prx/libkernel/CMakeLists.txt
PR 24917 core/libs/prx/libkernel/CMakeLists.txt
docs/dev/debt/libkernel.md

@github-actions github-actions Bot added libkernel docs needs rebase Conflicts with main, rebase needed labels Oct 24, 2026
@MarcZX10

Copy link
Copy Markdown
Contributor

The declared dependency #9099 has merged. The current PR is still DIRTY against main; a read-only merge-tree preview shows a content conflict in docs/dev/debt/libkernel.md (the Equeue source merges cleanly). Please refresh the branch on current main and resolve the debt entry while preserving this PR’s pipe/socket details, then rerun the focused event tests on the refreshed head. The reported run was against #9099’s older head, so it does not validate the current integration state.

@oneandonlydean oneandonlydean self-assigned this Oct 25, 2026
@rocklouis055
rocklouis055 force-pushed the feat/equeue-pipe-write-lowat-on9099 branch from e673953 to 2dec842 Compare October 25, 2026 07:57
@rocklouis055

Copy link
Copy Markdown
Contributor Author

@MarcZX10 thanks. Rebased on main after #9099 merged; the head is now 2dec842521, a single commit. The debt conflict is resolved on top of #9099's final entries: the regular-file entry (with the lseek note) and the new shared-memory entry are kept as on main, and only this PR's two changes are applied (the pipe entry covering both ends, and the low-watermark sentence on the socket entry). The test conflict was only the error constants, which main now takes from KernelErrors.hpp. On that head, Linux, Release: guest_socket_events passes (also 20 times with ctest --repeat until-fail:20), and guest_equeue_events, guest_kqueue, guest_socket_pair, guest_socket_read_write, guest_socket_descriptors and guest_socket_on_non_socket pass. Conventions report only the existing debt-length warning. Depends on is now none.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@rocklouis055 The new low-watermark assignment converts the unsigned size to int64_t without a range check. On a stream socket, size 0x8000000000000000 becomes INT64_MIN, so the data < lowWater check no longer filters ordinary readable/writable events. Please handle sizes that cannot be represented before storing the watermark, and add bounded boundary coverage around INT64_MAX and INT64_MAX+1 without allocating those sizes.

Please also drop the new throw assertions for the wrong pipe ends and the datagram watermark in GuestSocketEvents.cpp (lines 73–74 and 266). They pin unimplemented behavior. Keep the pipe readiness/EOF/EPIPE and supported stream-watermark coverage; the production throws and debt can stay.

The new positive pipe-write assertions are unconditional, but GuestSockets::PipeWriteState still explicitly throws on macOS. Please restrict that supported-path test to the platforms that implement pipe write readiness, while retaining the existing pipe-read and stream-watermark coverage on macOS.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 25, 2026
@rocklouis055

Copy link
Copy Markdown
Contributor Author

@oneandonlydean thanks, all three addressed in 54ffdb28c5:

  • Unrepresentable sizes: the watermark is now min(size, INT64_MAX). A watermark above INT64_MAX bytes cannot be reached anyway, so capping keeps it unreachable and only end of file fires the event; the debt entry says the size is capped. Bounded coverage: with 3 bytes queued on a stream socket, read events with sizes INT64_MAX, INT64_MAX + 1 and SIZE_MAX each time out instead of firing. With the previous unchecked conversion restored locally, guest_socket_events aborts on that check; with the cap it passes.
  • Throw assertions: the wrong-pipe-end and datagram-watermark Rejects checks are removed; the production throws and the debt stay. The pipe readiness, EV_EOF, EPIPE and stream-watermark coverage remain.
  • macOS: the pipe write-event block is under #ifndef __APPLE__; the pipe read and stream watermark checks still run there.

Linux, Release: guest_socket_events passes (also 20 times with ctest --repeat until-fail:20), and guest_equeue_events and guest_kqueue pass; conventions report only the existing debt-length warning. Windows and macOS not run here.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@rocklouis055 One more small change in Equeue.cpp around line 847: the new code sets event.lowWater = min(size, INT64_MAX) for every socket event, including sizes 0 and 1. Before this PR a size of 1 or less kept the default watermark of 0, and the PR description also says only sizes above 1 change it. With size 1 the event no longer fires for data == 0 readiness (a zero-length datagram, or a write with no free space). Something like size > 1 ? min(size, INT64_MAX) : 0 keeps the old behaviour for 0 and 1.

@ycbuzi

ycbuzi commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Windows run of 54ffdb28c5 merged onto main 63a863d3b0 (88430223a8, clean). Windows 11 Home 10.0.26200, WinLibs MinGW-w64 GCC 15.2.0 (ucrt-posix-seh r7), Release, BUILD_TESTING=ON.

  • Built guest_socket_event_tests with no errors or warnings.
  • ctest --repeat until-fail:2: guest_socket_events passes both runs.
  • Control: with core/libs/prx/libkernel/Equeue/Equeue.cpp from main and this PR's test, it aborts with sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented, so the pipe write-event path is what the test now reaches on Windows.

Not run: a title. AI-assisted: yes (Claude Code)

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@oneandonlydean right, thanks. Fixed in 84da0e3307: event.lowWater = size > 1 ? min(size, INT64_MAX) : 0, so sizes 0 and 1 keep the default watermark of 0 as before this PR. Added a check for it: a connected loopback datagram socket with a size-1 read event receives a zero-length datagram and the event fires with data 0. With the previous head's assignment restored locally, that check aborts; with this one it passes. Linux, Release: guest_socket_events passes 20 times with ctest --repeat until-fail:20. Not run on Windows.

@ycbuzi thanks for the Windows run and the control.

@ahmadmuj ahmadmuj 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 head 84da0e33070c merged onto main 0119103fa9ed (clean merge), Linux x86-64 (WSL2 Ubuntu 24.04, GCC 13.3), Release.

What I ran:

  • guest_socket_events on the merge: passes, 20/20 with --repeat until-fail:20. guest_equeue_events and guest_kqueue pass too.
  • Controls with this PR's test: main's Equeue.cpp aborts with sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented; the 54ffdb28c5 assignment (watermark for every size) fails (hangs to the 20 s ctest timeout); an unchecked static_cast<std::int64_t>(size) aborts. So the new checks catch all three.

Two things I think are worth fixing, one minor:

  1. Re-adding a socket event keeps the old watermark. AddDescriptorEvent passes the new lowWater to KernelEqueuePrivate::AddEvent, but for an event that already exists that only updates deadline, interval and udata (Equeue.cpp:475-477). kevent goes through ModifyKnote, which replaces lowWater (Kqueue.cpp:415), matching the kevent debt entry ("a later change of the knote replaces it as kqueue_register replaces kn_sdata"). Before this PR the mark was always 0 on this path, so this is new. Probe on the merge, stream socket with 3 bytes queued:

    • sceKernelAddReadEvent(eq, reader, 6, …) then sceKernelAddReadEvent(eq, reader, 1, …): the wait times out (mark is still 6)
    • size 1 then size 6: the event fires with data 3 (mark is still 1)

    Updating lowWater for an existing socket event (as ModifyKnote does) fixes it, and an add-6-then-add-1 check would cover it.

  2. Sizes above INT64_MAX are capped, where kevent throws. DescriptorLowWater throws on a NOTE_LOWAT mark below 1 (Kqueue.cpp:167), and a size above INT64_MAX is exactly such a negative mark if it reaches kn_sdata the way this PR models it. The kevent measurements entry also records the console firing at once for a mark of -1 on a drained stream socket. So under the PR's own model sceKernelAddReadEvent(eq, s, SIZE_MAX, …) would fire at once on the console, while here it never fires short of EOF. Throwing for those sizes, as kevent does, fits the throw-on-unknown rule better than picking a behaviour. The INT64_MAX + 1 and SIZE_MAX checks would then become Rejects-style or go away.

  3. Minor: a write event re-added on a pipe after the read end closed returns EPIPE (Equeue.cpp:836 runs before the existing-event lookup) and keeps the old udata. kevent checks EPIPE only for a new knote (Kqueue.cpp:475 to AddDescriptorKnote), as FreeBSD 11.4 runs pipe_kqfilter only on attach. Example: sceKernelAddWriteEvent(eq, p[1], 1, a), close(p[0]), sceKernelAddWriteEvent(eq, p[1], 1, b) gives EPIPE here and success through kevent. (Read from the code, not run.)

Not run: Windows, macOS.

@xXPBSXx

xXPBSXx commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Windows run of the exact head 84da0e3307, merged locally onto main 19fe176dda (clean merge). The earlier Windows run in this thread covered 54ffdb28c5, which does not have the loopback datagram check added in the last commit.

  • Host: Windows 10 19045, MinGW-w64 GCC 15.2, Release; the build finished with ninja exit code 0.
  • guest_socket_events fails 3 of 3 runs with exit code 0xc0000409; guest_equeue_events and guest_kqueue pass.
  • The failing check is the new one for a connected loopback datagram socket: after sceKernelAddReadEvent(blocking, datagram, 1, nullptr) and an empty send, the wait returns one event for the datagram, but its data is 1, and the test requires 0 (the line Require(count == 1 && events[0].ident == ... && events[0].data == 0)). I found this by printing the event fields from a temporary copy of the test: count=1 ident=7 datagram=7 data=1 filter=-1 flags=0x1, the same in 3 of 3 runs.
  • Control with Equeue.cpp from main and this PR's test (same base and build directory): fails 3 of 3 too, but earlier and for another reason: sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented. So this control does not isolate the datagram check.
  • Not measured: why Windows reports 1 here, Linux, macOS, a second Windows host.

AI-assisted (Claude Code).

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@rocklouis055 xXPBSXx's Windows run above shows guest_socket_events failing 3 of 3 on this exact head (84da0e3, merged onto main 19fe176dda). It fails in the new check for a connected loopback datagram socket: after sceKernelAddReadEvent and an empty send, the wait returns the event with data 1 where the test expects 0. Could you look at why Windows reports 1 there, and either fix the Windows path or explain why 0 is the right expectation? We're holding the merge until guest_socket_events passes on Windows.

@ycbuzi

ycbuzi commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

On the Windows failure xXPBSXx reported: the data 1 comes from Winsock's FIONREAD. It isn't the watermark change.

GuestSockets::Ready (Socket/src/Udp.cpp) reads data with ioctlsocket(FIONREAD) on Windows and ioctl(FIONREAD) elsewhere (SO_NREAD for datagrams on macOS). On Linux, FIONREAD on a UDP socket gives the size of the next datagram, so a queued zero-length datagram reads 0. Winsock gives something else. A standalone probe here (connected loopback UDP pair, Windows 11 26200, WinLibs GCC 15.2.0):

queued ioctlsocket(FIONREAD) recv(..., MSG_PEEK)
nothing 0 (WSAPoll 0) WSAEWOULDBLOCK
one 0-byte datagram 1 0
a 0-byte, then a 3-byte datagram 3 0
two 0-byte datagrams 1 0

So Winsock reports the total queued bytes, and 1 when only zero-length datagrams are queued. A peek reports the next datagram's size, the value the Linux and macOS paths give.

Peeking for datagram sockets on Windows fixes it. Locally tested, not pushed:

 #ifdef _WIN32
         unsigned long available = 0;
         if (ioctlsocket(socket->value, FIONREAD, &available) == 0) *data = static_cast<std::int64_t>(available);
+        if (socket->type == 2 && available != 0) {
+            static thread_local char next[65536];
+            const int size = ::recv(socket->value, next, sizeof(next), MSG_PEEK);
+            if (size >= 0) *data = size;
+        }
 #else
  • With it, onto main 47f9cee2cd: guest_socket_events, guest_equeue_events, guest_kqueue, guest_socket_read_write, guest_socket_options, guest_socket_descriptor_flags and guest_udp pass 3 of 3 (--repeat until-fail:3).
  • Without it, guest_socket_events fails as reported (0xc0000409).

The buffer is 64 KiB because, per the Winsock recv documentation, a datagram bigger than the buffer makes recv return SOCKET_ERROR with WSAEMSGSIZE instead of a size. I didn't test that path. Only Ready reads it, so MSG_PEEK leaves the datagram queued. Stream sockets keep FIONREAD.

AI-assisted: yes (Claude Code)

@wachi35676

Copy link
Copy Markdown
Contributor

Windows run of head 84da0e33070c merged onto main 90f918fa7. Windows 11 10.0.26300, WinLibs GCC 15.2.0, Release.

  • guest_equeue_events passes.
  • guest_socket_events fails 3/3 on Windows (0xc0000409). Main's version passes 3/3 in the same build. The failing check is the new zero-length datagram case:
    send_nid_postfix(datagram, "", 0, 0) -> read event: count=1 ident=7 filter=-1 data=1   (test expects data == 0)
    
    On Windows, the event's data comes from ioctlsocket(FIONREAD) (Socket/src/Udp.cpp readiness). Winsock reports 1 for a queued empty datagram. A standalone check on a connected loopback UDP socket: send(s, "", 0, 0), then FIONREAD = 1, recv = 0, and FIONREAD afterwards = 0. So the new assertion holds on Linux but not on Windows. Options are to measure a datagram's real length on Windows (for example recv with MSG_PEEK into a buffer), or to skip that check on Windows with a debt note.
  • With main's Equeue.cpp, the test aborts earlier at the new pipe write event (sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented). So the pipe and low-watermark parts are covered, and they pass on Windows up to the datagram case.

AI-assisted: yes (Claude Code); results above were run on this machine.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@rocklouis055 ycbuzi has traced the Windows data=1 failure to FIONREAD in GuestSockets::Ready and supplied a local before/after probe. The watermark fix can stay; this does not justify changing the zero-datagram expectation to 1. Please reconcile the Windows datagram byte count and rerun the updated socket/equeue tests.

If you use MSG_PEEK, keep readiness queries nonblocking when another reader drains the datagram between poll and peek, and cover an empty queue, a zero-length datagram, zero followed by a nonempty datagram, and unchanged stream behavior. The posted local patch and runs are useful evidence, but they are not in the current head yet.

@rocklouis055

Copy link
Copy Markdown
Contributor Author

Thanks @xXPBSXx and @wachi35676 for the Windows runs, @ycbuzi for tracing it to FIONREAD, and @ahmadmuj for the review. All addressed in 8e19a7affc:

Windows datagram size (Socket/src/Udp.cpp): when Winsock's FIONREAD is nonzero on a datagram socket, Ready peeks the next datagram with an overlapped WSARecv(MSG_PEEK) into a 64 KiB buffer. If the peek would wait, because another reader took the datagram between the poll and the peek, it is cancelled with CancelIoEx and data is 0, so the readiness query never blocks, also on a blocking socket. Stream sockets keep FIONREAD. The expectation stays 0, as on Linux and macOS (next datagram's size).

The test now covers an empty queue (times out), a zero-length datagram (data 0), a zero-length then a 3-byte datagram (data 0, then 3 after the first recv, then empty again). The stream checks are unchanged. I can't build on Windows here: the new code has no diagnostics in a clang x86_64-windows-gnu syntax check, but it needs a Windows run. Not tested: whether the peek clears a pending WSAECONNRESET (noted in the new debt entry).

@ahmadmuj's points:

  1. Re-add keeps the old mark: AddEvent now replaces lowWater on an existing event, as ModifyKnote does. Test: INT64_MAX then 1 fires with data 3, then 6 times out. Removing the line makes the test abort.
  2. Sizes above INT64_MAX: now throw, as DescriptorLowWater does for marks below 1, instead of picking a behaviour. @oneandonlydean, this replaces the cap you asked for earlier: the size is still checked before it's stored, but the INT64_MAX + 1 and SIZE_MAX checks are dropped, since they would pin a throw. INT64_MAX still times out.
  3. EPIPE on a re-add: EPIPE is now returned only when no write event exists yet. A re-add succeeds and replaces udata. Test added; returning EPIPE on every re-add makes it abort.

Linux, Release: guest_socket_events, guest_equeue_events, guest_kqueue and guest_udp pass 20 times with --repeat until-fail:20. A Windows rerun of guest_socket_events on this head would be very welcome.

AI-assisted: yes (Claude Code).

@ycbuzi

ycbuzi commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

@rocklouis055 A Windows run of 8e19a7affc: Windows 11 Home 10.0.26200, WinLibs GCC 15.2.0 r7 (MinGW-w64 UCRT), Release. 8e19a7affc merged onto main 128e47a83b with no conflicts, run with ctest --repeat until-fail:3.

  • guest_socket_events, guest_udp, guest_equeue_events and guest_kqueue pass 3 of 3.
  • Control with main's Equeue.cpp and Udp.cpp: guest_socket_events aborts (0xc0000409) with sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented. That's the pipe write event in PipeReadEvents(), the first function main() calls, so this control never gets to the datagram checks. The other three pass. I've queued a second control with only main's Udp.cpp, which should show whether the new datagram cases fail without NextDatagramSize. I'll add it here.

I also checked the new peek path's Winsock behaviour on this machine with a standalone probe, built with the same toolchain, that calls WSARecv(MSG_PEEK) exactly as NextDatagramSize does (overlapped, CancelIoEx on WSA_IO_PENDING, then WSAGetOverlappedResult(..., TRUE, ...)):

  • Empty queue: the peek returns WSA_IO_PENDING on a blocking socket and on a nonblocking one alike. CancelIoEx then makes WSAGetOverlappedResult fail with 995 (WSA_OPERATION_ABORTED), so data is 0 and nothing waits. Afterwards FIONREAD is still 0 and WSAPoll isn't readable, so the cancelled peek leaves nothing behind.
  • Pending WSAECONNRESET (the "Not tested" point in the debt entry), with SIO_UDP_CONNRESET on, connected and unconnected: after a send to a closed loopback port, FIONREAD is 1 and WSAPoll is readable. The peek fails with 10054, and the next recv still returns 10054, then 10035. So the peek doesn't consume the error. With an error and then a 3-byte datagram queued, FIONREAD is 3, the peek fails with 10054 (so data stays at FIONREAD's 3), and the two recvs return 10054, then 3.
  • With SIO_UDP_CONNRESET off, as main sets it on every datagram socket in Udp.cpp: the port-unreachable leaves no trace at all. FIONREAD is 0, WSAPoll isn't readable, and recv returns 10035. With a datagram queued after it, the peek returns 3 and recv returns 3. So on main's sockets this case doesn't reach the peek.

AI-assisted: yes (Claude Code)

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@ycbuzi thank you, that settles the open point. I replaced the "not tested" sentence in the Windows datagram debt entry with your measurement in 790f2708e7 (docs only, no code change since 8e19a7affc): a pending WSAECONNRESET fails the peek, data stays at FIONREAD's count, the error stays queued for the next recv, and main's datagram sockets turn SIO_UDP_CONNRESET off, so the reply never reaches the peek.

Looking forward to the Udp.cpp-only control.

AI-assisted: yes (Claude Code).

@ycbuzi

ycbuzi commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

@rocklouis055 The Udp.cpp-only control, on 790f2708e7 (code identical to 8e19a7affc; the new commit only touches the debt entry). It's this PR merged onto main 4e43321bd6, with main's Socket/src/Udp.cpp and everything else from the PR, same toolchain as before:

  • guest_socket_events aborts 3 of 3. To find which check fails, I made a local build where Require prints its line before aborting (diagnostic only, not pushed). It stops at GuestSocketEvents.cpp:292 every time: count == 1 && events[0].ident == datagram && events[0].data == 0. That's the read event for the first zero-length datagram.
  • The same instrumented test on the full PR passes 3 of 3.

So on Windows the new datagram case fails without NextDatagramSize and passes with it. This matches the earlier probe: FIONREAD reports 1 when only a zero-length datagram is queued, and main's Ready passes that through as data.

AI-assisted: yes (Claude Code)

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@rocklouis055 Thanks for 8e19a7affc and the docs follow-up. The overlapped peek fixes the zero-length datagram count (ycbuzi's Udp.cpp-only control confirms it), but one part of the earlier nonblocking-readiness request is still open.

In Socket/src/Udp.cpp, NextDatagramSize (around lines 910-928) calls CancelIoEx and then WSAGetOverlappedResult(..., TRUE, ...), and ignores the result of CancelIoEx. CancelIoEx only requests cancellation, and TRUE waits until the I/O actually completes. Ready is reached from PollEvents while the equeue mutex is held (Equeue.cpp around 413-425), before the wait deadline is checked (444-446), so a delayed cancellation acknowledgment still blocks readiness and every other queue operation.

Could you keep the poll-to-peek path nonblocking through cancellation completion, with a lifetime for the pending OVERLAPPED, event and buffer that stays valid until the I/O completes? Just switching TRUE to FALSE, or returning while stack-owned I/O may still be pending, would trade this for a use-after-return. Please also handle a failed CancelIoEx and the race where normal completion wins over the cancel, and add a control for a delayed cancellation or a racing reader. The existing zero, zero-then-three, empty, stream and error cases should stay, and the expected data stays 0.

@ycbuzi

ycbuzi commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

@oneandonlydean @rocklouis055 Some measurements of the cancellation path that may help with the redesign. A standalone probe on this Windows 11 machine (26200, MinGW-w64 GCC 15.2.0) runs the PR's exact sequence: overlapped WSARecv(MSG_PEEK) into 64 KiB, CancelIoEx on WSA_IO_PENDING, then WSAGetOverlappedResult(..., TRUE, ...), timed from the cancel to the wait's return. Loopback UDP, nonblocking socket. Two runs of each case:

case pended peeks completed (completion won the race) aborted (995) CancelIoEx failed wait p50 / p99 / p99.9 / max
empty queue 20,000 0 20,000 0 1.9 / 2.0 / 3.3–3.9 / 7.5–17.8 µs
5 s, with a sender thread and another thread draining the same socket 937k–955k 151k–170k 766k–804k 12.8k–13.2k 2.5 / 11–12 / 16–17 / 547–723 µs
  • Every CancelIoEx failure was ERROR_NOT_FOUND: the I/O had already completed, and in every one of those cases the TRUE wait returned success with the datagram size. So ignoring CancelIoEx's result didn't hang anything here. The completion-wins race is common under contention, about 1 in 6 pended peeks.
  • The wait is short but not zero, and its tail grows with load: up to 0.72 ms here, which per your reading of PollEvents happens with the equeue mutex held. These are measurements from one machine with no layered providers or filter drivers on loopback, so they don't give an upper bound. Your point about not waiting under the mutex stands.

The probe source is short; I can attach it if it's useful for the new control.

AI-assisted: yes (Claude Code)

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@ycbuzi Thanks, that's really useful. The completion-wins race at about 1 in 6 under contention and the wait tail up to 0.72 ms are exactly the cases the new control should cover. Yes, please attach the probe source, so @rocklouis055 can use it as a starting point for the delayed-cancellation and racing-reader control.

@ycbuzi

ycbuzi commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

@oneandonlydean @rocklouis055 Here's the probe. It's standalone, needs only Winsock, and isn't AnyPS5 code. Peek is NextDatagramSize's sequence with counters and a timer around the wait.

Build and run: g++ -O1 -Wall -o probe.exe probe.cpp -lws2_32, then probe.exe. It runs 20,000 empty-queue peeks, then 5 s with a sender thread and a draining reader on the same loopback socket, and prints the outcome counts and the wait percentiles.

probe.cpp
// How long does #10645's peek wait in WSAGetOverlappedResult(..., TRUE) after CancelIoEx, and which way do races go?
// 1. Empty queue: peek, cancel, wait; N times; latency distribution.
// 2. Racing traffic: a sender thread sends small datagrams while another reader thread drains them; the probe thread
//    runs the same peek/cancel/wait loop; counts immediate completions, pended-then-completed, pended-then-aborted,
//    CancelIoEx failures, and the wait latency.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <thread>
#include <vector>

struct Outcome {
    int immediate = 0, completed = 0, aborted = 0, otherError = 0, cancelFailed = 0;
    int cancelFailedNotFound = 0, cancelFailedThenCompleted = 0;
    std::vector<double> waitMicros;
};

static void Peek(SOCKET s, Outcome& out) {
    static thread_local char next[65536];
    WSABUF buffer{sizeof(next), next};
    WSAOVERLAPPED overlapped{};
    overlapped.hEvent = WSACreateEvent();
    DWORD received = 0, flags = MSG_PEEK;
    if (WSARecv(s, &buffer, 1, &received, &flags, &overlapped, nullptr) == 0) {
        ++out.immediate;
    } else if (WSAGetLastError() == WSA_IO_PENDING) {
        const auto start = std::chrono::steady_clock::now();
        const BOOL cancelled = CancelIoEx(reinterpret_cast<HANDLE>(s), &overlapped);
        if (!cancelled) { ++out.cancelFailed; if (GetLastError() == ERROR_NOT_FOUND) ++out.cancelFailedNotFound; }
        const BOOL ok = WSAGetOverlappedResult(s, &overlapped, &received, TRUE, &flags);
        if (!cancelled && ok) ++out.cancelFailedThenCompleted;
        const int error = ok ? 0 : WSAGetLastError();
        out.waitMicros.push_back(std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - start).count());
        if (ok) ++out.completed;
        else if (error == WSA_OPERATION_ABORTED) ++out.aborted;
        else ++out.otherError;
    } else {
        ++out.otherError;
    }
    WSACloseEvent(overlapped.hEvent);
}

static void Report(const char* label, Outcome& out) {
    auto& w = out.waitMicros;
    std::sort(w.begin(), w.end());
    auto at = [&](double q) { return w.empty() ? 0.0 : w[std::min(w.size() - 1, static_cast<std::size_t>(q * w.size()))]; };
    std::printf("%s\n  immediate=%d pended+completed=%d pended+aborted(995)=%d other-error=%d CancelIoEx-failed=%d (ERROR_NOT_FOUND %d, then completed %d)\n"
                "  wait after cancel (us), %zu samples: p50=%.1f p99=%.1f p99.9=%.1f max=%.1f\n",
                label, out.immediate, out.completed, out.aborted, out.otherError, out.cancelFailed, out.cancelFailedNotFound, out.cancelFailedThenCompleted, w.size(), at(0.5), at(0.99),
                at(0.999), w.empty() ? 0.0 : w.back());
}

int main() {
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    SOCKET target = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    bind(target, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
    sockaddr_in name{};
    int length = sizeof(name);
    getsockname(target, reinterpret_cast<sockaddr*>(&name), &length);
    u_long nonblocking = 1;
    ioctlsocket(target, FIONBIO, &nonblocking);

    Outcome empty;
    for (int i = 0; i < 20000; ++i) Peek(target, empty);
    Report("1. empty queue, 20000 peeks (nonblocking socket)", empty);

    std::atomic<bool> stop{false};
    std::atomic<long> sent{0}, drained{0};
    std::thread sender([&] {
        SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        while (!stop.load()) {
            if (sendto(s, "abc", 3, 0, reinterpret_cast<sockaddr*>(&name), sizeof(name)) == 3) ++sent;
            std::this_thread::yield();
        }
        closesocket(s);
    });
    std::thread reader([&] {
        char buffer[64];
        while (!stop.load()) {
            if (recv(target, buffer, sizeof(buffer), 0) >= 0) ++drained;
            else std::this_thread::yield();
        }
    });
    Outcome racing;
    const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(5);
    while (std::chrono::steady_clock::now() < until) Peek(target, racing);
    stop = true;
    sender.join();
    reader.join();
    Report("2. 5 s with a sender and a draining reader thread on the same socket", racing);
    std::printf("  datagrams sent=%ld drained by the reader=%ld\n", sent.load(), drained.load());
    closesocket(target);
    WSACleanup();
    return 0;
}

AI-assisted: yes (Claude Code)

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@oneandonlydean you're right, the TRUE wait could still block under the equeue mutex. @ycbuzi, thanks for the Udp.cpp-only control and the cancellation timings. Reworked in 0b01993063:

  • No wait: after CancelIoEx, NextDatagramSize checks the peek with WSAGetOverlappedResult(..., FALSE, ...). Readiness never waits for the cancellation to complete.
  • Lifetime: the OVERLAPPED, its event and the 64 KiB buffer are a record in a process-wide pool that is never freed (static auto* pool = new ..., as in Signals.cpp). They aren't on the stack or owned by the socket, so a socket closed while its peek is pending can't free memory the kernel still writes to. If the cancellation is still pending (WSA_IO_INCOMPLETE), the record is parked and data is 0. A later call reuses a parked record only once HasOverlappedIoCompleted reports it done. The pool only grows to the number of peeks in flight at once.
  • Completion wins over the cancel: the non-waiting check succeeds and reports that datagram's size.
  • Failed CancelIoEx: its result no longer decides anything. If the I/O had already completed (ERROR_NOT_FOUND, as @ycbuzi measured), the check reports it. Otherwise the record stays parked until the peek completes.
  • Control: the test now runs a sender (20,000 alternating zero-length and 3-byte datagrams) and a racing reader draining with MSG_DONTWAIT on the same socket, while the read event is polled with a 1 ms timeout. Every reported data must be 0 or 3, and the queue must be empty afterwards. On Linux an instrumented run saw both sizes reported during the race. The empty, zero-length, zero-then-three, stream and error cases are unchanged, and data for a zero-length datagram stays 0.

I can't force a delayed cancellation from the test, so the racing reader is the control. It shows correct values and no hang, but it can't show that the old code waited. @ycbuzi's probe would show that, and I'm happy to add it as a Windows-only test if it fits.

Linux, Release: guest_socket_events, guest_equeue_events, guest_kqueue and guest_udp pass 20 times (--repeat until-fail:20). The Windows code passes a clang x86_64-windows-gnu syntax check with no diagnostics in the new lines, but it needs a Windows run on this head.

AI-assisted: yes (Claude Code).

rocklouis055 and others added 5 commits November 1, 2026 16:04
…ing reset

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ncellation

- NextDatagramSize checks the cancelled peek with WSAGetOverlappedResult
  without waiting, so Ready never waits under the equeue mutex.
- The OVERLAPPED, event and buffer live in a process-wide pool that is never
  freed; a peek whose cancellation is still pending is reused only after
  HasOverlappedIoCompleted reports it done.
- A completion that wins over the cancel reports its size; a failed
  CancelIoEx leaves the peek parked.
- Test: a sender and a racing reader on one datagram socket while the read
  event is polled; every reported size is 0 or 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ntil it completes

- A peek that WSARecv left pending stays reserved whatever
  WSAGetOverlappedResult reports, and is reused only once
  HasOverlappedIoCompleted reports it done.
- The pool moves to Socket/include/SubmittedRecords.hpp, and
  guest_socket_submitted_records checks that a submitted record is not
  handed out again before completion and is reused after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…est on MinGW

- The peek event is created when a pool record is acquired, and a failed
  WSACreateEvent is tried again on the next acquire instead of leaving the
  record without an event.
- guest_socket_submitted_records checks that a failed preparation is retried
  and the record then reused.
- guest_socket_submitted_record_tests links libc and configures Windows
  unwinding like guest_socket_event_tests, so it links on MinGW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l check

The racing reader can stop before the sender's last datagram is readable,
as on macOS loopback. After both threads join, the test now reads each
remaining datagram while the read event reports it, checking its size, and
then requires the event to time out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rocklouis055
rocklouis055 force-pushed the feat/equeue-pipe-write-lowat-on9099 branch from 459808d to bf70e27 Compare November 1, 2026 10:43
@rocklouis055

Copy link
Copy Markdown
Contributor Author

Rebased on main ba8dcc6ae8 and fixed the macOS failure, now at bf70e27f7d.

macOS racing-reader check (thanks @Gonic0 for the probe, it pointed straight at it): the reader thread could stop before the sender's last datagram became readable, so the final "queue empty" wait found it. After both threads join, the test now reads each late datagram while the read event reports it (checking data is 0 or 3 and that recv returns that size), then requires the timeout. To reproduce the macOS case on Linux, I made the reader drain nothing: the old final check fails and the new drain passes. No library code changed.

Rebase: the only conflict was the shared-memory entry next to this PR's entries in docs/dev/debt/libkernel.md. main's text is kept, and this PR's diff of that file is unchanged. Linux, Release, on the rebuilt tree: guest_socket_events, guest_socket_submitted_records, guest_udp, guest_equeue_events and guest_kqueue pass 20 times (--repeat until-fail:20). Thanks @wachi35676 for the Windows 10/10 and the NextDatagramSize control.

Order:

The order is recorded in the description as proposed, not agreed. A macOS rerun on bf70e27f7d would be welcome.

AI-assisted: yes (Claude Code).

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 1, 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.

Re-checked — new head, no blocking findings

The new head changes only the final check after the racing threads join, and I found no blocking defect, but that check no longer fails when a datagram stays queued without an event, which was the symptom the earlier changes-requested review cited.

What I ran

Exact head bf70e27f7db6fe20e56d788ee44c0de1c9266ed9, previously reviewed head 459808d639d933e070dd37115367317657461313, current main e67cc818696fd6e6c58ac80adc6550c54aed68e8 (merge preview clean, no declared dependencies). Environment: Debian 12, Python 3.11.2, git 2.39.5. No build, no compiler, no CTest.

python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 10645
python3 tools/pr_stack_check.py 10645 --repo boykopovar/AnyPS5
git diff 2742004ed28f765c7147db0e0269ff5868e9eb6f 459808d639d933e070dd37115367317657461313 -- <7 PR files>
git diff ba8dcc6ae82a5c4443efd93bbb99dfa91faf7fa4 bf70e27f7db6fe20e56d788ee44c0de1c9266ed9 -- <7 PR files>
python3 tools/pr_abi_audit.py --repo <local clone> --base e6f57307fa7f47165d7fc1bee945abdb2f6816e7 --head bf70e27f7db6fe20e56d788ee44c0de1c9266ed9 --json
python3 tools/pr_test_quality.py --root <git archive of the head> --json core/libs/tests/GuestSocketEvents.cpp core/libs/tests/GuestSocketSubmittedRecords.cpp

The precheck's ABI and test-quality helpers could not find their scripts in its isolated head tree, so I ran both helpers by hand as listed. The changed-line comparison was run on the PR's own patches at both heads.

Results

Check Result
Conventions and PR template (precheck) Passed.
git diff --check (precheck) Passed.
Live stack and merge preview against main (precheck) Clean.
Changed lines, old head vs new head Only one hunk differs: the final check in core/libs/tests/GuestSocketEvents.cpp. The product files (Equeue.cpp, Udp.cpp, SubmittedRecords.hpp, libkernel CMakeLists.txt) have identical changed lines at both heads.
pr_abi_audit.py (by hand) Passed: 58 symbols, 0 findings.
pr_test_quality.py (by hand) Two heuristic findings, both possible-unregistered-cpp-test. Both files are registered in core/libs/prx/libkernel/CMakeLists.txt through ${LIBS_INCLUDE_DIR}/tests/... paths, so these are false positives.
Hosted CI (precheck snapshot) Passed: conventions, library-portability, report, eligibility. Pending: labels, windows. Skipped: linux, register-context, relinker, relinker-asan, write-watch.
Build, CTest, macOS Not run.
Unedited command output
$ python3 tools/pr_abi_audit.py --repo /marc/AnyPS5 --base e6f57307fa7f47165d7fc1bee945abdb2f6816e7 --head bf70e27f7db6fe20e56d788ee44c0de1c9266ed9 --json
status: passed; symbols: 58; findings: []

$ python3 tools/pr_test_quality.py --root <archive> --json core/libs/tests/GuestSocketEvents.cpp core/libs/tests/GuestSocketSubmittedRecords.cpp
findings: possible-unregistered-cpp-test (core/libs/tests/GuestSocketEvents.cpp, line 1)
findings: possible-unregistered-cpp-test (core/libs/tests/GuestSocketSubmittedRecords.cpp, line 1)

changed-line diff (old head vs new head, PR files only):
< +    Require(sceKernelWaitEqueue(blocking, events.data(), events.size(), &count, &shortTimeout) == SCE_KERNEL_ERROR_ETIMEDOUT);
> +    char late[8];
> +    int drained = SCE_OK;
> +    while ((drained = sceKernelWaitEqueue(blocking, events.data(), events.size(), &count, &shortTimeout)) == SCE_OK) {
> +        Require(count == 1 && (events[0].data == 0 || events[0].data == 3));
> +        Require(recv_nid_postfix(datagram, late, sizeof(late), 0x80) == events[0].data);
> +    }
> +    Require(drained == SCE_KERNEL_ERROR_ETIMEDOUT);

Findings

Blocking: None.

Non-blocking:

  • At the earlier head, the test asserted a single timeout after the racing threads joined, so any event for a queued datagram failed the test. At the new head, the loop at lines 361-364 drains each event and exits on the first timeout. If a datagram stays queued and no event is reported, the test now passes without checking the queue. The racing reader already relies on a negative recv with flag 0x80 meaning "empty", so an emptiness check can use the same convention. Suggested addition after line 365:
    Require(drained == SCE_KERNEL_ERROR_ETIMEDOUT);
    Require(recv_nid_postfix(datagram, late, sizeof(late), 0x80) < 0);

Sources

Not verified

  • The Linux repeats the author reports (20 runs of the event suite on the rebuilt tree) and the hosted Linux job, which is skipped on this head, were not run or re-checked here.
  • macOS was not run. The rerun on bf70e27f7db6fe20e56d788ee44c0de1c9266ed9 that the description requests is still needed; this review cannot provide it.
  • The merge order proposed in the PR description is a maintainer decision and is not answered by this review.

…the drain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@rocklouis055

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Good catch. The drain loop alone would pass with a datagram stuck in the queue and no event reported. I added your check in b1d851b: after the final timeout, recv(datagram, ..., 0x80) must return a negative value, i.e. the queue is empty.

  • Negative control: sending one more 3-byte datagram just before that check fails the test, and removing the send makes it pass again.
  • Linux: guest_socket_events passed 20 of 20 runs at b1d851b (Ubuntu 26.04, GCC 15.2, Release).
  • Not run: macOS. The rerun requested in the description is still needed, now on b1d851b.

AI-assisted: yes (Claude Code)

@rocklouis055
rocklouis055 requested a review from MarcZX10 November 1, 2026 15:35

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

Re-checked — new head, changes requested

The new head adds the missing final queue-empty assertion, but the required merge order with three open overlapping PRs is still explicitly unagreed.

What I ran

Reviewed head b1d851bf4752c6cb42f4aba29bc4004fbd666ba1, based on e6f57307fa7f47165d7fc1bee945abdb2f6816e7; the live preview onto current main f2d874c1fdccf781c0fa5d86619bb5dd8894b958 is clean. Environment: Debian 12 x86-64, Python 3.11.2, Git 2.39.5. No compiler or build was run.

python3 tools/pr_precheck.py --repo boykopovar/AnyPS5 --pr 10645
python3 tools/pr_abi_audit.py --repo /marc/AnyPS5 --base e6f57307fa7f47165d7fc1bee945abdb2f6816e7 --head b1d851bf4752c6cb42f4aba29bc4004fbd666ba1
python3 tools/pr_test_quality.py --root /tmp/anyps5-pr-precheck/boykopovar-AnyPS5-pr-10645-b1d851bf4752/head-b1d851bf4752-41251437 core/libs/prx/libkernel/CMakeLists.txt core/libs/prx/libkernel/Equeue/Equeue.cpp core/libs/prx/libkernel/Socket/include/SubmittedRecords.hpp core/libs/prx/libkernel/Socket/src/Udp.cpp core/libs/tests/GuestSocketEvents.cpp core/libs/tests/GuestSocketSubmittedRecords.cpp docs/dev/debt/libkernel.md
git diff --check e6f57307fa7f47165d7fc1bee945abdb2f6816e7...b1d851bf4752c6cb42f4aba29bc4004fbd666ba1
python3 tools/pr_stack_check.py 10645 --repo boykopovar/AnyPS5
git show b1d851bf4752c6cb42f4aba29bc4004fbd666ba1:core/libs/prx/libkernel/CMakeLists.txt | grep -n -A18 'add_test_executable(guest_socket_event_tests'

Results

Check Result Note
Patch and conventions passed One existing debt-entry length warning.
Export/NID audit passed 58 symbols; no findings.
Test registration passed Both added C++ tests are in CMake.
Test-quality heuristic passed Two unregistered-test warnings are false positives; CMake uses ${LIBS_INCLUDE_DIR} paths.
Current-main merge preview passed Clean against current main.
Hosted checks passed Windows and required metadata checks pass; Linux and specialized jobs were skipped.
C++ tests on this head not run No exact-head build was performed.
Selected raw check output
# PR precheck report — checks failed
Head unchanged at completion: **True**
Base unchanged at completion: **True**

| Check | Status | Command / reason |
|---|---|---|
| diff_check | passed | `git diff --check e6f57307fa7f47165d7fc1bee945abdb2f6816e7...b1d851bf4752c6cb42f4aba29bc4004fbd666ba1` |
| conventions_and_pr_template | passed | `/usr/bin/python3 tools/check_conventions.py --base e6f57307fa7f47165d7fc1bee945abdb2f6816e7 --head b1d851bf4752c6cb42f4aba29bc4004fbd666ba1 --title feat(libkernel): add pipe write events and socket low watermarks to sceKernelAdd*Event --body /tmp/anyps5-pr-precheck/boykopovar-AnyPS5-pr-10645-b1d851bf4752/pr-body.md` |
| changed_export_abi_audit | failed | `/usr/bin/python3 tools/pr_abi_audit.py ...`; script absent from detached snapshot |
| live_dependency_and_mergeability_check | passed | `/usr/bin/python3 /marc/AnyPS5/tools/pr_stack_check.py 10645 --repo boykopovar/AnyPS5 --output-dir /tmp/anyps5-pr-precheck/boykopovar-AnyPS5-pr-10645-b1d851bf4752/stack` |
| test_quality_heuristics | failed | Script absent from detached snapshot |

Manual rerun:
ABI audit: passed

core/libs/tests/GuestSocketEvents.cpp:1: possible-unregistered-cpp-test: Changed C++ test source path was not found literally in CMake files; inspect registration, generated source lists, and workflow coverage.
core/libs/tests/GuestSocketSubmittedRecords.cpp:1: possible-unregistered-cpp-test: Changed C++ test source path was not found literally in CMake files; inspect registration, generated source lists, and workflow coverage.
Heuristic findings require manual interpretation.

Target branch tip: `f2d874c1fdccf781c0fa5d86619bb5dd8894b958`
All heads unchanged: **True**
Dependency order: #10645
- PR #10645: **clean** against current base; head `b1d851bf4752c6cb42f4aba29bc4004fbd666ba1`
No declared PR dependencies were found in the target PR chain.

Negative control

Assertion Code change Result
The datagram queue is empty after the final equeue timeout. Author reports sending an extra datagram before the assertion. Author reports the test fails; I did not independently run this control.

Findings

Blocking

  • The PR proposes landing before #12682, #12688 and #12700, but says this order is “Not yet agreed.” Those PRs remain open, and the transport PR records an overlapping Udp.cpp seam with #10645 and says the second PR must rebase. The repository requires overlapping authors to agree on order and declare it with Depends on. Please coordinate the order with the affected authors and update the PR order/dependency declaration to reflect that agreement.

Non-blocking

  • The reported macOS rerun is still outstanding on this head. The earlier macOS failure was reported against an older head; Windows CI passes, but this does not verify the macOS case.

Sources

Not verified

No local build, CTest, macOS rerun, or console behavior was verified. The negative control is author-reported only.

To get this to a good state

Please reach and record an order agreement with the overlapping PR authors, then update the relevant Depends on declarations. I will rerun the same no-build checks on the new head.

@B-Howell

B-Howell commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

On the open merge-order point in MarcZX10's last review: on current main (b28bb77217), this PR's overlap with #12688 and #12700 comes down to one line. Both add an #include at the same place in Socket/src/Udp.cpp: this PR adds SubmittedRecords.hpp, and they add SocketSelectDeadline.hpp. With both includes kept, nothing else conflicts. #12682 merges cleanly with this PR.

I tested that combination locally (nothing pushed): main + #12700 at c962560591 (its branch already contains #12682, #12688 and #12149) + this PR's b1d851bf47, with both includes kept.

  • WSL2 Ubuntu 22.04 (GCC 11.4.0) and Windows 11 Pro 26300 (WinLibs GCC 15.2.0 r7), both Release: guest_socket_events, guest_socket_submitted_records, guest_equeue_events, guest_kqueue, guest_kqueue_cleared_race, guest_tcp and guest_udp pass 3 of 3 on both.
  • main + feat(libkernel): cancel blocked POSIX writes with partial progress #12700 alone passes the same six tests that exist there (guest_socket_submitted_records is this PR's), so the stack adds no regression on that side.
  • This PR alone on main: the same 7 pass 3 of 3 on both hosts. The description's last Windows run was on 8e19a7affc, so this is a Windows run of the current head. Control (Windows): with main's Equeue.cpp and Udp.cpp, guest_socket_events aborts with sceKernelAddWriteEvent: descriptor that is neither a socket nor a regular file not implemented.

So either landing order costs one #include line. What is left is for the authors to state the order under Depends on. Not run: macOS, which the description still asks for.

AI-assisted: yes (Claude Code)

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@B-Howell thank you for composing and running the stack on both hosts, and for the Windows run of b1d851bf47; that also covers the head the description had not tested on Windows yet.

@Felipebmaitan on the landing order: I'm sorry I never answered your proposal from Oct 27. It was for #11969, which has since closed, and your stack is now #12682 → #12688 → #12700. As B-Howell showed, and as your audits on #12688 and #12700 say, the only overlap is the adjacent #include in Socket/src/Udp.cpp, and neither side calls the other's code.

I propose #10645 first, then your stack, which keeps both includes when it next rebases. #10645 has no open prerequisites and merges cleanly with main, while #12700 still waits on #12149, #9019 and its Windows/bench gates, so this order doesn't hold either of us up. If you would rather land your stack first, say so: I'll declare Depends on: #12700 here and rebase after it merges. Could you confirm one order or the other? I'll record it under Depends on on this PR.

AI-assisted: yes (Claude Code)

@tkcm01

tkcm01 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

macOS run of b1d851bf47 on an Apple M4.

Tree:

Targeted: the 22 existing socket, equeue, kqueue, udp and pipe tests plus guest_socket_submitted_records, --repeat until-fail:5 under -j4.

  • guest_socket_events passed 5/5, then 30/30 alone. The racing-reader failure did not show up.
  • guest_socket_submitted_records passed 5/5.
  • guest_udp and guest_kqueue abort with no message, with and without this PR.
  • The pipe write-event block in GuestSocketEvents.cpp is under #ifndef __APPLE__, so it does not run here.

Negative control (this PR's two test files and their CMake lines on the same base, no source changes):

  • guest_socket_events aborts 3/3 with sceKernelAddReadEvent: low watermark not implemented.
  • GuestSocketSubmittedRecords.cpp does not compile, since SubmittedRecords.hpp is new.

Full ctest -j4 --timeout 120: 97 failed before (3845 tests) and after (3846). The failing sets differ only by two GPU tests:

  • agc_driver_scratch_pool failed only before and passes on a rerun.
  • agc_driver_label_after_import_copy failed only after ("56064 of 262144 destination bytes not yet copied"). On the base without this PR it passed in the full run and in 4 of 5 repeats, then failed 10 of 10 alone, so it is a timing race unrelated to this PR.

Not tested: Linux, Windows, and pipe write events on macOS.

AI-assisted: yes

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@tkcm01 thank you for the macOS run, and for running the negative control and checking the full suite before and after. guest_socket_events passing 30/30 alone on b1d851bf47 settles the racing-reader failure reported on the older head. I've added your run to the description. The guest_udp/guest_kqueue aborts and the AGC copy race happen without this PR too, so I've left them out of it.

@Felipebmaitan a gentle ping on the order question above: #10645 first and then your stack, or your stack first and I declare Depends on: #12700 here. Either works for me; it only needs your confirmation so both PRs can record it.

AI-assisted: yes (Claude Code)

@rocklouis055

Copy link
Copy Markdown
Contributor Author

@oneandonlydean could you check where this one stands? The head b1d851bf47 merges cleanly with main, and the Linux, Windows (B-Howell) and macOS (tkcm01) runs pass. The last open point was the merge order with #12682/#12688/#12700, which share one adjacent #include in Udp.cpp. I'm happy to go either first or after them with Depends on.

Is anything still missing here, or can it be merged?

AI-assisted: yes (Claude Code)

@malekaifa

Copy link
Copy Markdown
Contributor

Fresh overlap audit against the current heads (source-only; no combined build in this pass):

So whichever lands second must deliberately preserve both behaviors. If #12700 lands first, #10645's rebase needs to re-add the submitted-record peek helper and the Ready datagram-size correction. If #10645 lands first, the #12682 -> #12688 -> #12700 rebase needs to carry those pieces forward.

Given #10645 is independently clean and already has Linux/Windows/macOS validation, #10645 first remains the simpler landing order; the transport stack can then rebase once and preserve the three pieces above. This does not by itself resolve MarcZX10's formal order blocker: it still needs the owners/maintainer to agree on that order and the composed head to be re-tested.

@Felipebmaitan @MarcZX10 @oneandonlydean

AI-assisted: yes

@oneandonlydean
oneandonlydean dismissed MarcZX10’s stale review November 26, 2026 04:37

10645 dismiss MarcZX10 CR 5729042250 (1 Nov, on b1d851b = live head)

CR: merge order with the #12682 -> #12688 -> #12700 stack not agreed.
Settled: B-Howell 2 Nov tested main + #12700 stack + this head on Linux and Windows, both includes kept: the 7 socket/equeue tests pass 3/3. malekaifa 23 Nov audit: #10645 first is the simpler order; whichever lands second must keep SubmittedRecords peek + Ready datagram-size correction. Today #12682, #12688, #12700 are all CONFLICTING with main while #10645 is MERGEABLE, so #10645 lands first and the stack's rebase carries both behaviours (noted for that stack's reviewers).
Fresh PASS HIGH NO by pr-review1 on b1d851b 26 Nov (notes/10645-b1d851bf47.md, key claims verified at Equeue.cpp:892-914).

@oneandonlydean
oneandonlydean merged commit d2409ce into boykopovar:main Nov 26, 2026
15 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.