common: finish file reads that hit GPU-protected guest pages (ASTRO BOT) #2141

Open
github-bot wants to merge 3 commits from github-bot/gh-2141 into main AGit
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 19:34 UTC · original
Nawid3333:fix/protected-guest-file-reads → main · +346 −5 · 6 files · 3 commits · open

ASTRO BOT (PPSA21564) sometimes stops at its own assert Room.cpp:787 ODX Definition is not found (or ObjectDefinitionContext.cpp:89) right after Read 0 bytes of an .odxb file. Zero-byte reads like this happen when the read buffer lies in guest pages the GPU tracker keeps write-protected: the host read delivers nothing.

Cause. The page manager write-protects guest pages it watches for GPU synchronization. ReadFile writes the buffer from kernel mode, which cannot raise the emulator's fault handler, so it fails with ERROR_NOACCESS (998) or ERROR_INVALID_USER_BUFFER (1784) and SysFileRead returns a short read; on Linux fread stops with EFAULT. A user-mode copy into the same page faults into HandleGpuFault -> RenderContext::HandleFault(Write), the path a guest CPU store takes, which invalidates the caches over the page and unprotects it.

Why after the read, not before. KernelRead and KernelPread already invalidate the destination before the host read (fileSystem.cpp:697, :824). A lab build logged the page-manager state of every short read in one ASTRO BOT run: in 12 of 13, no page of the buffer was watched right before the host read and some or all of its pages were watched again right after; the 13th already had 15 of its 32 pages watched again before the call. Every buffer was fully GPU-mapped and none was a buffer-cache region. The pages are watched again between the preparation and the end of the read, so preparing earlier does not close the gap. The copy after the failure goes through the fault handler for whichever pages are protected when it touches them.

Change.

  • SysFileRead records the file position before every read. When the read fails this way, Windows seeks back to that position and reads again from there, Linux continues after the bytes already delivered; both read through a thread-local 1 MiB buffer, up to the end of the file, and copy each chunk into the guest buffer in user mode. After a recovery the file position is the start plus the bytes delivered.
  • Each chunk is copied only if the guest may write it: InstallGpuResources installs a probe that accepts a range only when every guest mapping in it has CPU write permission. A read into memory the guest cannot write stays short, as on main, instead of making a read-only page writable.
  • The probe hook and the Linux recovery come from #1165 (@⁠NeySlim), the Windows bounce buffer from #838 (@⁠ew-sudo); both are co-authors of the commit. #1430 (@⁠Almo7aya) reads KernelRead/KernelPread/KernelPreadv through a host buffer every time; this change keeps reading directly into guest memory and copies only after a failed read.

Tests.

  • KernelFileSystemTests (TestReadsIntoProtectedPages, from #1165): KernelPread, KernelRead and KernelPreadv fill buffers that cross into a write-protected page, a read past EOF recovers only the bytes the file holds, and a destination with a no-access page stays short without crashing.
  • BufferCacheDirtyGarbageCollection (new case): a 12-byte file read ends in a page whose buffer is GPU-written; all 12 bytes must arrive, the range must be CPU-modified and no longer GPU-dirty, and the next buffer lookup must see the new words. The same file is also read through KernelPread, into a fully GPU-mapped range (the pre-read invalidation unprotects it) and into a range whose first page is not GPU-mapped (the invalidation skips it, so the recovery has to deliver the bytes), each from a cleared destination and with the same checks.
  • On my PC (Windows 11, RX 9070 XT) TestReadsIntoProtectedPages and BufferCacheDirtyGarbageCollection pass; with the recovery branch switched off (main's behaviour) both fail: pread fills a buffer that crosses into a write-protected page and kernel-read bytes (the KernelPread read into the partly mapped range).

In-game. ASTRO BOT, boot-and-mash script, one build (this change + #2022) with a lab switch that turns the recovery off (= main's read path), three runs each in the order fix, base, base, fix, fix, base:

  • with this change: 12, 8 and 10 failed ReadFile calls (998 and 1784, 128 KiB to 11 MiB), every one recovered in full, 0 zero-byte reads;
  • recovery off: 21, 7 and 6 zero-byte reads.
  • Frame pacing: base 32, 25 and 26 hitches per run, this change 25 and 20; the first fix run (shaders still cold after a short warm-up) had 39.
  • Earlier crash check on two main-based builds: 1 of 8 boots on each arm died in the game's assert right after Read 0 bytes of an .odxb.

Fork CI on the PR head (4b8336a1f): the Linux, Windows and macOS builds and tests pass.

Written with Claude Code and OpenAI Codex (AI): the port, the tests, the diagnostics and the measurements, run on my PC; reviewed by me.

**@⁠Nawid3333** on GitHub · 2026-11-06 19:34 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141) `Nawid3333:fix/protected-guest-file-reads` → `main` · +346 −5 · 6 files · 3 commits · open ASTRO BOT (PPSA21564) sometimes stops at its own assert `Room.cpp:787 ODX Definition is not found` (or `ObjectDefinitionContext.cpp:89`) right after `Read 0 bytes` of an `.odxb` file. Zero-byte reads like this happen when the read buffer lies in guest pages the GPU tracker keeps write-protected: the host read delivers nothing. **Cause.** The page manager write-protects guest pages it watches for GPU synchronization. `ReadFile` writes the buffer from kernel mode, which cannot raise the emulator's fault handler, so it fails with `ERROR_NOACCESS` (998) or `ERROR_INVALID_USER_BUFFER` (1784) and `SysFileRead` returns a short read; on Linux `fread` stops with `EFAULT`. A user-mode copy into the same page faults into `HandleGpuFault` -> `RenderContext::HandleFault(Write)`, the path a guest CPU store takes, which invalidates the caches over the page and unprotects it. **Why after the read, not before.** `KernelRead` and `KernelPread` already invalidate the destination before the host read (`fileSystem.cpp:697`, `:824`). A lab build logged the page-manager state of every short read in one ASTRO BOT run: in 12 of 13, no page of the buffer was watched right before the host read and some or all of its pages were watched again right after; the 13th already had 15 of its 32 pages watched again before the call. Every buffer was fully GPU-mapped and none was a buffer-cache region. The pages are watched again between the preparation and the end of the read, so preparing earlier does not close the gap. The copy after the failure goes through the fault handler for whichever pages are protected when it touches them. **Change.** - `SysFileRead` records the file position before every read. When the read fails this way, Windows seeks back to that position and reads again from there, Linux continues after the bytes already delivered; both read through a thread-local 1 MiB buffer, up to the end of the file, and copy each chunk into the guest buffer in user mode. After a recovery the file position is the start plus the bytes delivered. - Each chunk is copied only if the guest may write it: `InstallGpuResources` installs a probe that accepts a range only when every guest mapping in it has CPU write permission. A read into memory the guest cannot write stays short, as on main, instead of making a read-only page writable. - The probe hook and the Linux recovery come from #1165 (@⁠NeySlim), the Windows bounce buffer from #838 (@⁠ew-sudo); both are co-authors of the commit. #1430 (@⁠Almo7aya) reads `KernelRead`/`KernelPread`/`KernelPreadv` through a host buffer every time; this change keeps reading directly into guest memory and copies only after a failed read. **Tests.** - `KernelFileSystemTests` (`TestReadsIntoProtectedPages`, from #1165): `KernelPread`, `KernelRead` and `KernelPreadv` fill buffers that cross into a write-protected page, a read past EOF recovers only the bytes the file holds, and a destination with a no-access page stays short without crashing. - `BufferCacheDirtyGarbageCollection` (new case): a 12-byte file read ends in a page whose buffer is GPU-written; all 12 bytes must arrive, the range must be CPU-modified and no longer GPU-dirty, and the next buffer lookup must see the new words. The same file is also read through `KernelPread`, into a fully GPU-mapped range (the pre-read invalidation unprotects it) and into a range whose first page is not GPU-mapped (the invalidation skips it, so the recovery has to deliver the bytes), each from a cleared destination and with the same checks. - On my PC (Windows 11, RX 9070 XT) `TestReadsIntoProtectedPages` and `BufferCacheDirtyGarbageCollection` pass; with the recovery branch switched off (main's behaviour) both fail: `pread fills a buffer that crosses into a write-protected page` and `kernel-read bytes` (the `KernelPread` read into the partly mapped range). **In-game.** ASTRO BOT, boot-and-mash script, one build (this change + #2022) with a lab switch that turns the recovery off (= main's read path), three runs each in the order fix, base, base, fix, fix, base: - with this change: 12, 8 and 10 failed `ReadFile` calls (998 and 1784, 128 KiB to 11 MiB), every one recovered in full, 0 zero-byte reads; - recovery off: 21, 7 and 6 zero-byte reads. - Frame pacing: base 32, 25 and 26 hitches per run, this change 25 and 20; the first fix run (shaders still cold after a short warm-up) had 39. - Earlier crash check on two main-based builds: 1 of 8 boots on each arm died in the game's assert right after `Read 0 bytes` of an `.odxb`. Fork CI on the PR head (4b8336a1f): the Linux, Windows and macOS builds and tests pass. Written with Claude Code and OpenAI Codex (AI): the port, the tests, the diagnostics and the measurements, run on my PC; reviewed by me.
Host file reads write guest memory from kernel mode, which cannot raise the
emulator's fault handler. A ReadFile into a page the GPU tracker keeps
write-protected fails with ERROR_NOACCESS or ERROR_INVALID_USER_BUFFER and
the guest gets a short read; on Linux fread stops with EFAULT. ASTRO BOT
then asserts on a lost .odxb read.

Retry the failed bytes through a bounce buffer whose user-mode copy faults
into the normal handler, chunk by chunk, for destinations the guest may
write, and only for bytes the file still holds. Other destinations keep the
short read.

The probe hook and the Linux recovery come from #1165, the Windows bounce
from #838.

Co-authored-by: NeySlim <[email protected]>
Co-authored-by: ew-sudo <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The protected-read case now also reads the fixture through KernelPread,
once into a fully GPU-mapped range (the pre-read invalidation unprotects
it) and once into a range whose first page is not GPU-mapped (the
invalidation skips it and the recovery delivers the bytes), and checks
the guest bytes, the CPU ownership and the next buffer lookup. Each
read starts from a cleared destination. The final seek of the Linux
recovery is dropped: the stream is already at start + w there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:15:56 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original · edited 2026-11-06 22:49 UTC

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The file I/O interface adds a callback for checking destination memory. Linux and Windows reads use the callback to recover from selected destination access errors and report bytes read. GPU resource installation registers a probe that checks virtual-range coverage and CPU-write permission, and clears the callback when resources are removed. Tests cover protected-page reads, reads past EOF, inaccessible destinations, and GPU cache state.

Suggested reviewers: nmzik

Change: Bug fix

Merge Risk: Low · up to 4b833

This PR recovers short file reads into GPU-protected guest pages. The remaining risks are test-only: gaps in coverage of the probe's rejection paths, and a temporary file that can be left behind after a failed assertion. It is mergeable with owner awareness.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Title check Passed The title describes recovery of file reads into GPU-protected guest pages, which is the main change.
Description check Passed The description covers the read recovery, destination probe, and tests in the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 5 files. (1 skipped: 1 too large.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 549d3630a0 and 4b8336a1ff.

Files selected for processing: 2

  • src/common/platform/sysLinuxFileIO.cpp
  • tests/ShaderRecompilerComputeTests.cpp
Files with no reviewable changes: 1

  • src/common/platform/sysLinuxFileIO.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#issuecomment-6693779774) · edited 2026-11-06 22:49 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/2141?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- recent_review_status_start --> No actionable comments were generated in the recent review. <!-- recent_review_status_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> The file I/O interface adds a callback for checking destination memory. Linux and Windows reads use the callback to recover from selected destination access errors and report bytes read. GPU resource installation registers a probe that checks virtual-range coverage and CPU-write permission, and clears the callback when resources are removed. Tests cover protected-page reads, reads past EOF, inaccessible destinations, and GPU cache state. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"4b8336a1ff7e8d0a0f760e7e74fea82edcdfc9ce" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · up to <code>4b833</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🔵 Low** · up to `4b833` --> <!-- final_review_risk_coverage:{"sourceCommitId":"4b8336a1ff7e8d0a0f760e7e74fea82edcdfc9ce","coveredCommitId":"4b8336a1ff7e8d0a0f760e7e74fea82edcdfc9ce","kind":"reviewed"} --> This PR recovers short file reads into GPU-protected guest pages. The remaining risks are test-only: gaps in coverage of the probe's rejection paths, and a temporary file that can be left behind after a failed assertion. It is mergeable with owner awareness. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <br> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title describes recovery of file reads into GPU-protected guest pages, which is the main change. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description covers the read recovery, destination probe, and tests in the changeset. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> <br> **Explanation** Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 5 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2141)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>Share</strong></summary> <dl> <dd> <br> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <!-- tips_end --> <!-- recent_review_start --> <h6> <details> <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Recent review info</strong></summary> <dl> <dd> <br> <!-- review_info_content --> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/182161eb3e31439d97433607a8aa95463c56a9cc/.coderabbit.yaml>) - **Commit**: [182161e](<https://github.com/KytyPS5/KytyPS5/commit/182161eb3e31439d97433607a8aa95463c56a9cc>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `b3bedab5-0e2c-47ae-bb71-217eca57554d` </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</strong></summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 549d3630a06aad88419b2564a5af64655efd36b2 and 4b8336a1ff7e8d0a0f760e7e74fea82edcdfc9ce. </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</strong></summary> <dl> <dd> <br> * `src/common/platform/sysLinuxFileIO.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-no-changes-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-no-changes.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files with no reviewable changes: 1</strong></summary> <dl> <dd> <br> * src/common/platform/sysLinuxFileIO.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- recent_review_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/scripts/watch_inbox.py line 380 (outdated):

@@ -0,0 +1,502 @@
+#!/usr/bin/env python3
+"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue.
+
+Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the
+checkpoint (the time window start and the PR conditions already reported) from hidden
+markers in the inbox issue body, collects upstream comments, reviews and PR state changes
+since then, posts at most one comment and moves the checkpoint to the run start.
+
+Links use www.github.com (redirects to github.com): GitHub does not turn those into
+cross-references, so the upstream threads get no "mentioned this" timeline entries.
+"""
+
+import datetime as dt
+import json
+import os
+import re
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+API = "https://api.github.com"
+UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5")
+FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5")
+USER = os.environ.get("WATCH_USER", "Nawid3333")
+WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt")
+DRY_RUN = os.environ.get("DRY_RUN") == "1"
+
+INBOX_TITLE = "Watch inbox"
+INBOX_LABEL = "watch-inbox"
+FIRST_RUN_WINDOW = dt.timedelta(hours=6)
+MAX_WINDOW = dt.timedelta(days=3)
+# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet
+# listed by the API (clock skew, eventual consistency) is never skipped.
+SETTLE = dt.timedelta(seconds=60)
+MAX_SHOWN = 15
+MAX_LISTED = 200
+MERGE_CHECKS_PER_RUN = 8
+MIN_RATE_REMAINING = 100
+MAX_PAGES = 10
+FAILED = {"failure", "timed_out", "startup_failure"}
+
+SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->")
+STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->")
+MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE)
+
+
+class RateLow(Exception):
+    pass
+
+
+class Api:
+    def __init__(self, token):
+        self.token = token
+        self.calls = 0
+        self.remaining = None
+
+    def request(self, method, url, params=None, body=None):
+        if not url.startswith("https://"):
+            url = API + url
+        if params:
+            url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
+        if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING:
+            raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}")
+        data = json.dumps(body).encode() if body is not None else None
+        req = urllib.request.Request(url, data=data, method=method)
+        req.add_header("Accept", "application/vnd.github+json")
+        req.add_header("X-GitHub-Api-Version", "2022-11-28")
+        req.add_header("User-Agent", "watch-inbox")
+        req.add_header("Authorization", "Bearer " + self.token)
+        if data is not None:
+            req.add_header("Content-Type", "application/json")
+        for attempt in (1, 2):  # one retry for transient server and network errors
+            self.calls += 1
+            try:
+                with urllib.request.urlopen(req, timeout=60) as resp:
+                    headers = resp.headers
+                    raw = resp.read()
+                break
+            except urllib.error.HTTPError as err:
+                self._note_rate(err.headers)
+                if err.code >= 500 and attempt == 1:
+                    time.sleep(5)
+                    continue
+                detail = err.read().decode("utf-8", "replace")[:300]
+                raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None
+            except urllib.error.URLError:
+                if attempt == 2:
+                    raise
+                time.sleep(5)
+        self._note_rate(headers)
+        return (json.loads(raw) if raw else None), headers
+
+    def _note_rate(self, headers):
+        value = headers.get("X-RateLimit-Remaining") if headers else None
+        if value is not None:
+            self.remaining = int(value)
+
+    def get(self, path, params=None):
+        return self.request("GET", path, params)[0]
+
+    def pages(self, path, params):
+        url, query, page = path, dict(params, per_page=100), 0
+        while url and page < MAX_PAGES:
+            data, headers = self.request("GET", url, query)
+            yield from data
+            url, query, page = next_link(headers, "next"), None, page + 1
+        if url:
+            print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped")
+
+    def tail(self, path, pages=2):
+        """Items of the last `pages` pages of an ascending list, oldest first."""
+        data, headers = self.request("GET", path, {"per_page": 100})
+        last = next_link(headers, "last")
+        if not last:
+            return data
+        data, headers = self.request("GET", last)
+        if pages > 1 and next_link(headers, "prev"):
+            data = self.request("GET", next_link(headers, "prev"))[0] + data
+        return data
+
+
+def next_link(headers, rel):
+    for part in (headers.get("Link") or "").split(","):
+        match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part)
+        if match and match.group(2) == rel:
+            return match.group(1)
+    return None
+
+
+def parse_ts(text):
+    return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
+
+
+def iso(moment):
+    return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+GHOST = {"login": "ghost", "type": "User"}
+
+
+def same_user(login):
+    return (login or "").lower() == USER.lower()
+
+
+def is_bot(user):
+    return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]")
+
+
+def www(url):
+    return url.replace("https://github.com/", "https://www.github.com/", 1)
+
+
+def load_watch_list(path):
+    numbers = set()
+    try:
+        with open(path, encoding="utf-8") as handle:
+            for line in handle:
+                numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0]))
+    except FileNotFoundError:
+        print(f"::warning::{path} not found; watching only own threads and mentions")
+    return numbers
+
+
+# ---- text handling --------------------------------------------------------------------
+
+
+def strip_markup(body):
+    text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S)
+    previous = None
+    while previous != text:  # innermost <details> first, CodeRabbit nests them
+        previous = text
+        text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I)
+    text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text)  # images and badges
+    text = re.sub(r"\[\s*\]\([^)]*\)", " ", text)  # links left empty by that
+    text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S)  # code blocks
+    text = re.sub(r"<[^>]+>", " ", text)
+    return text
+
+
+def plain(line):
+    line = re.sub(r"^\s*#+\s*", "", line)
+    line = line.replace("**", "").replace("__", "")
+    line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line)
+    return line.strip(" -*|")
+
+
+def summary(body, bot):
+    lines = []
+    for line in strip_markup(body).splitlines():
+        line = line.strip()
+        if line.startswith(">"):
+            if not bot:
+                continue  # a human quoting earlier text
+            line = re.sub(r"^(>\s*)+", "", line)  # bots put their headline in a quote
+        line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip()
+        if line and not re.fullmatch(r"[-*_=|: ]+", line):
+            lines.append(line)
+    if not lines:
+        return ""
+    if not bot:
+        return " ".join(lines)
+    # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a
+    # bold title; reviews and summaries carry a bold headline in their first lines.
+    if "|" in lines[0] and len(lines) > 1:
+        return f"{plain(lines[0])} · {plain(lines[1])}"
+    for line in lines[:4]:
+        if re.fullmatch(r"\*\*[^*]+\*\*", line):
+            return plain(line)
+    first = plain(lines[0])
+    if len(first) < 40 and len(lines) > 1:
+        first = f"{first} · {plain(lines[1])}"
+    return first
+
+
+def safe(text, limit):
+    """One markdown line that mentions, links and references nobody."""
+    text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)  # markdown links: keep the text
+    text = re.sub(r"https?://\S+", "(link)", text)
+    text = " ".join(text.split())
+    if len(text) > limit:
+        text = text[: limit - 1].rstrip() + "…"
+    text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]")
+    text = text.replace("@", "@\u200b")
+    text = re.sub(r"#(?=\d)", "#\u200b", text)
+    return text
+
+
+# ---- inbox and checkpoint -------------------------------------------------------------
+
+
+def find_inbox(api):
+    def pick(issues):
+        found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i]
+        found.sort(key=lambda i: (i["state"] != "open", i["number"]))
+        return found[0] if found else None
+
+    inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"}))
+    if inbox is None:
+        inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"}))
+    if inbox is None and not DRY_RUN:
+        try:
+            api.request("POST", f"/repos/{FORK}/labels",
+                        body={"name": INBOX_LABEL, "color": "0e8a16",
+                              "description": "Fork-only upstream watch inbox"})
+        except RuntimeError as err:
+            if "HTTP 422" not in str(err):
+                raise
+        inbox = api.request("POST", f"/repos/{FORK}/issues", body={
+            "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0]
+        print(f"created inbox issue #{inbox['number']}")
+    return inbox
+
+
+def read_checkpoint(api, inbox, now):
+    body = (inbox or {}).get("body") or ""
+    since = SINCE_RE.search(body)
+    if since is None and inbox and inbox.get("comments"):
+        for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")):
+            if SINCE_RE.search(comment["body"] or ""):
+                body = comment["body"]
+                since = SINCE_RE.search(body)
+                break
+    if since is None:
+        return now - FIRST_RUN_WINDOW, set()
+    return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body))
+
+
+def markers(since, state):
+    lines = [f"<!-- state: {key} -->" for key in sorted(state)]
+    return "\n".join(lines + [f"<!-- watch-since: {since} -->"])
+
+
+def inbox_body(since, state, calls):
+    text = (
+        "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever "
+        f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in "
+        f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}."
+    )
+    if since:
+        text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls."
+        text += "\n\n" + markers(since, state)
+    return text
+
+
+# ---- collection -----------------------------------------------------------------------
+
+
+class Collector:
+    def __init__(self, api, since, until, watch):
+        self.api, self.since, self.until, self.watch = api, since, until, watch
+        self.threads = {}
+        self.events = []
+
+    def in_window(self, stamp):
+        return stamp is not None and self.since <= parse_ts(stamp) < self.until
+
+    def remember(self, item):
+        pr = item.get("pull_request") or {}
+        self.threads[item["number"]] = {
+            "title": item["title"],
+            "author": (item.get("user") or GHOST)["login"],
+            "open": item["state"] == "open",
+            "closed_at": item.get("closed_at"),
+            "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")),
+            "url": item["html_url"],
+        }
+
+    def thread(self, number):
+        if number not in self.threads:
+            self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}"))
+        return self.threads[number]
+
+    def wanted(self, number, body):
+        if number in self.watch or MENTION_RE.search(body or ""):
+            return True
+        info = self.thread(number)
+        return info["open"] and same_user(info["author"])
+
+    def add(self, number, stamp, kind, url, user=None, body=None):
+        self.thread(number)  # the title, for render()
+        bot = bool(user) and is_bot(user)
+        author = user["login"].removesuffix("[bot]") if user else ""
+        self.events.append({"n": number, "at": stamp, "kind": kind, "url": url,
+                            "author": author, "bot": bot,
+                            "text": summary(body, bot) if body is not None else ""})
+
+    def threads_since(self):
+        params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)}
+        for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params):
+            self.remember(item)
+
+    def comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["issue_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"])
+
+    def review_comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["pull_request_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                where = c["path"].rsplit("/", 1)[-1]
+                line = c.get("line") or c.get("original_line")
+                kind = f"inline {where}:{line}" if line else f"inline {where}"
+                self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"])
+
+    def closures(self):
+        for number, info in self.threads.items():
+            if self.in_window(info["closed_at"]) and not info["open"] \
+                    and (number in self.watch or same_user(info["author"])):
+                self.add(number, info["closed_at"], "merged" if info["merged"] else "closed",
+                         info["url"])
+
+    def own_prs(self, previous):
+        """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet."""
+        prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"})
+               if same_user(p["user"]["login"])]
+        prs.sort(key=lambda p: p["number"])
+        runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs",
+                            {"actor": USER, "per_page": 100})["workflow_runs"]
+        recent = self.since - dt.timedelta(hours=1)
+        rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN))
+        turn = int(self.until.timestamp() // 600) % rounds
+        state = set()
+        for index, pr in enumerate(prs):
+            number, sha = pr["number"], pr["head"]["sha"][:7]
+            self.threads.setdefault(number, {
+                "title": pr["title"], "author": pr["user"]["login"], "open": True,
+                "closed_at": None, "merged": False, "url": pr["html_url"]})
+            updated = parse_ts(pr["updated_at"])
+            if updated >= self.since:
+                self.reviews(number)

Major · Functional Correctness · Heavy lift

Supported by static analysis

Script executed:

git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github
printf '\n--- inbox collector and scope ---\n'
nl -ba .github/scripts/watch_inbox.py | sed -n '1,120p;200,500p;500,660p'
printf '\n--- workflow and watch-list references ---\n'
rg -n -i -e 'watch inbox' -e 'watch-threads' -e 'watch_inbox' -e 'review submissions' -- .github || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 23922


Script executed:

git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github
printf '\n--- inbox collector and scope ---\n'
nl -ba .github/scripts/watch_inbox.py | sed -n '1,120p;200,660p'
printf '\n--- workflow and watch-list references ---\n'
rg -n -i -e 'watch inbox' -e 'watch-threads' -e 'watch_inbox' -e 'review submissions' -- .github || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 23914


Script executed:

rg -n -F -e '.reviews(' -e 'reviews(' -- .github/scripts/watch_inbox.py
nl -ba .github/watch-threads.txt | sed -n '1,15p'
nl -ba .github/workflows/watch-inbox.yml | sed -n '1,12p'

Repository: KytyPS5/KytyPS5

Length of output: 1294


Collect reviews on watched PRs and reviews that mention USER.

Collector.reviews runs only for USER’s open PRs. The inbox can therefore miss approvals, change requests, and review bodies on other watched PRs, including review-body mentions. The checkpoint then advances past those reviews.

Add review collection for watched PRs and mentions on other PRs. Preserve the existing filters and avoid duplicate reports for USER’s PRs.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806148) On `.github/scripts/watch_inbox.py` line 380 (outdated): ```diff @@ -0,0 +1,502 @@ +#!/usr/bin/env python3 +"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue. + +Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the +checkpoint (the time window start and the PR conditions already reported) from hidden +markers in the inbox issue body, collects upstream comments, reviews and PR state changes +since then, posts at most one comment and moves the checkpoint to the run start. + +Links use www.github.com (redirects to github.com): GitHub does not turn those into +cross-references, so the upstream threads get no "mentioned this" timeline entries. +""" + +import datetime as dt +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +API = "https://api.github.com" +UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5") +FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5") +USER = os.environ.get("WATCH_USER", "Nawid3333") +WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt") +DRY_RUN = os.environ.get("DRY_RUN") == "1" + +INBOX_TITLE = "Watch inbox" +INBOX_LABEL = "watch-inbox" +FIRST_RUN_WINDOW = dt.timedelta(hours=6) +MAX_WINDOW = dt.timedelta(days=3) +# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet +# listed by the API (clock skew, eventual consistency) is never skipped. +SETTLE = dt.timedelta(seconds=60) +MAX_SHOWN = 15 +MAX_LISTED = 200 +MERGE_CHECKS_PER_RUN = 8 +MIN_RATE_REMAINING = 100 +MAX_PAGES = 10 +FAILED = {"failure", "timed_out", "startup_failure"} + +SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->") +STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->") +MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE) + + +class RateLow(Exception): + pass + + +class Api: + def __init__(self, token): + self.token = token + self.calls = 0 + self.remaining = None + + def request(self, method, url, params=None, body=None): + if not url.startswith("https://"): + url = API + url + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING: + raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}") + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Accept", "application/vnd.github+json") + req.add_header("X-GitHub-Api-Version", "2022-11-28") + req.add_header("User-Agent", "watch-inbox") + req.add_header("Authorization", "Bearer " + self.token) + if data is not None: + req.add_header("Content-Type", "application/json") + for attempt in (1, 2): # one retry for transient server and network errors + self.calls += 1 + try: + with urllib.request.urlopen(req, timeout=60) as resp: + headers = resp.headers + raw = resp.read() + break + except urllib.error.HTTPError as err: + self._note_rate(err.headers) + if err.code >= 500 and attempt == 1: + time.sleep(5) + continue + detail = err.read().decode("utf-8", "replace")[:300] + raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None + except urllib.error.URLError: + if attempt == 2: + raise + time.sleep(5) + self._note_rate(headers) + return (json.loads(raw) if raw else None), headers + + def _note_rate(self, headers): + value = headers.get("X-RateLimit-Remaining") if headers else None + if value is not None: + self.remaining = int(value) + + def get(self, path, params=None): + return self.request("GET", path, params)[0] + + def pages(self, path, params): + url, query, page = path, dict(params, per_page=100), 0 + while url and page < MAX_PAGES: + data, headers = self.request("GET", url, query) + yield from data + url, query, page = next_link(headers, "next"), None, page + 1 + if url: + print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped") + + def tail(self, path, pages=2): + """Items of the last `pages` pages of an ascending list, oldest first.""" + data, headers = self.request("GET", path, {"per_page": 100}) + last = next_link(headers, "last") + if not last: + return data + data, headers = self.request("GET", last) + if pages > 1 and next_link(headers, "prev"): + data = self.request("GET", next_link(headers, "prev"))[0] + data + return data + + +def next_link(headers, rel): + for part in (headers.get("Link") or "").split(","): + match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part) + if match and match.group(2) == rel: + return match.group(1) + return None + + +def parse_ts(text): + return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc) + + +def iso(moment): + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + +GHOST = {"login": "ghost", "type": "User"} + + +def same_user(login): + return (login or "").lower() == USER.lower() + + +def is_bot(user): + return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]") + + +def www(url): + return url.replace("https://github.com/", "https://www.github.com/", 1) + + +def load_watch_list(path): + numbers = set() + try: + with open(path, encoding="utf-8") as handle: + for line in handle: + numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0])) + except FileNotFoundError: + print(f"::warning::{path} not found; watching only own threads and mentions") + return numbers + + +# ---- text handling -------------------------------------------------------------------- + + +def strip_markup(body): + text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S) + previous = None + while previous != text: # innermost <details> first, CodeRabbit nests them + previous = text + text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I) + text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text) # images and badges + text = re.sub(r"\[\s*\]\([^)]*\)", " ", text) # links left empty by that + text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S) # code blocks + text = re.sub(r"<[^>]+>", " ", text) + return text + + +def plain(line): + line = re.sub(r"^\s*#+\s*", "", line) + line = line.replace("**", "").replace("__", "") + line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line) + return line.strip(" -*|") + + +def summary(body, bot): + lines = [] + for line in strip_markup(body).splitlines(): + line = line.strip() + if line.startswith(">"): + if not bot: + continue # a human quoting earlier text + line = re.sub(r"^(>\s*)+", "", line) # bots put their headline in a quote + line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip() + if line and not re.fullmatch(r"[-*_=|: ]+", line): + lines.append(line) + if not lines: + return "" + if not bot: + return " ".join(lines) + # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a + # bold title; reviews and summaries carry a bold headline in their first lines. + if "|" in lines[0] and len(lines) > 1: + return f"{plain(lines[0])} · {plain(lines[1])}" + for line in lines[:4]: + if re.fullmatch(r"\*\*[^*]+\*\*", line): + return plain(line) + first = plain(lines[0]) + if len(first) < 40 and len(lines) > 1: + first = f"{first} · {plain(lines[1])}" + return first + + +def safe(text, limit): + """One markdown line that mentions, links and references nobody.""" + text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) # markdown links: keep the text + text = re.sub(r"https?://\S+", "(link)", text) + text = " ".join(text.split()) + if len(text) > limit: + text = text[: limit - 1].rstrip() + "…" + text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]") + text = text.replace("@", "@\u200b") + text = re.sub(r"#(?=\d)", "#\u200b", text) + return text + + +# ---- inbox and checkpoint ------------------------------------------------------------- + + +def find_inbox(api): + def pick(issues): + found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i] + found.sort(key=lambda i: (i["state"] != "open", i["number"])) + return found[0] if found else None + + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"})) + if inbox is None: + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"})) + if inbox is None and not DRY_RUN: + try: + api.request("POST", f"/repos/{FORK}/labels", + body={"name": INBOX_LABEL, "color": "0e8a16", + "description": "Fork-only upstream watch inbox"}) + except RuntimeError as err: + if "HTTP 422" not in str(err): + raise + inbox = api.request("POST", f"/repos/{FORK}/issues", body={ + "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0] + print(f"created inbox issue #{inbox['number']}") + return inbox + + +def read_checkpoint(api, inbox, now): + body = (inbox or {}).get("body") or "" + since = SINCE_RE.search(body) + if since is None and inbox and inbox.get("comments"): + for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")): + if SINCE_RE.search(comment["body"] or ""): + body = comment["body"] + since = SINCE_RE.search(body) + break + if since is None: + return now - FIRST_RUN_WINDOW, set() + return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body)) + + +def markers(since, state): + lines = [f"<!-- state: {key} -->" for key in sorted(state)] + return "\n".join(lines + [f"<!-- watch-since: {since} -->"]) + + +def inbox_body(since, state, calls): + text = ( + "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever " + f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in " + f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}." + ) + if since: + text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls." + text += "\n\n" + markers(since, state) + return text + + +# ---- collection ----------------------------------------------------------------------- + + +class Collector: + def __init__(self, api, since, until, watch): + self.api, self.since, self.until, self.watch = api, since, until, watch + self.threads = {} + self.events = [] + + def in_window(self, stamp): + return stamp is not None and self.since <= parse_ts(stamp) < self.until + + def remember(self, item): + pr = item.get("pull_request") or {} + self.threads[item["number"]] = { + "title": item["title"], + "author": (item.get("user") or GHOST)["login"], + "open": item["state"] == "open", + "closed_at": item.get("closed_at"), + "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")), + "url": item["html_url"], + } + + def thread(self, number): + if number not in self.threads: + self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}")) + return self.threads[number] + + def wanted(self, number, body): + if number in self.watch or MENTION_RE.search(body or ""): + return True + info = self.thread(number) + return info["open"] and same_user(info["author"]) + + def add(self, number, stamp, kind, url, user=None, body=None): + self.thread(number) # the title, for render() + bot = bool(user) and is_bot(user) + author = user["login"].removesuffix("[bot]") if user else "" + self.events.append({"n": number, "at": stamp, "kind": kind, "url": url, + "author": author, "bot": bot, + "text": summary(body, bot) if body is not None else ""}) + + def threads_since(self): + params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)} + for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params): + self.remember(item) + + def comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["issue_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"]) + + def review_comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["pull_request_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + where = c["path"].rsplit("/", 1)[-1] + line = c.get("line") or c.get("original_line") + kind = f"inline {where}:{line}" if line else f"inline {where}" + self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"]) + + def closures(self): + for number, info in self.threads.items(): + if self.in_window(info["closed_at"]) and not info["open"] \ + and (number in self.watch or same_user(info["author"])): + self.add(number, info["closed_at"], "merged" if info["merged"] else "closed", + info["url"]) + + def own_prs(self, previous): + """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet.""" + prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"}) + if same_user(p["user"]["login"])] + prs.sort(key=lambda p: p["number"]) + runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs", + {"actor": USER, "per_page": 100})["workflow_runs"] + recent = self.since - dt.timedelta(hours=1) + rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN)) + turn = int(self.until.timestamp() // 600) % rounds + state = set() + for index, pr in enumerate(prs): + number, sha = pr["number"], pr["head"]["sha"][:7] + self.threads.setdefault(number, { + "title": pr["title"], "author": pr["user"]["login"], "open": True, + "closed_at": None, "merged": False, "url": pr["html_url"]}) + updated = parse_ts(pr["updated_at"]) + if updated >= self.since: + self.reviews(number) ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github printf '\n--- inbox collector and scope ---\n' nl -ba .github/scripts/watch_inbox.py | sed -n '1,120p;200,500p;500,660p' printf '\n--- workflow and watch-list references ---\n' rg -n -i -e 'watch inbox' -e 'watch-threads' -e 'watch_inbox' -e 'review submissions' -- .github || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 23922 --- Script executed: ```bash git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github printf '\n--- inbox collector and scope ---\n' nl -ba .github/scripts/watch_inbox.py | sed -n '1,120p;200,660p' printf '\n--- workflow and watch-list references ---\n' rg -n -i -e 'watch inbox' -e 'watch-threads' -e 'watch_inbox' -e 'review submissions' -- .github || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 23914 --- Script executed: ```bash rg -n -F -e '.reviews(' -e 'reviews(' -- .github/scripts/watch_inbox.py nl -ba .github/watch-threads.txt | sed -n '1,15p' nl -ba .github/workflows/watch-inbox.yml | sed -n '1,12p' ``` Repository: KytyPS5/KytyPS5 Length of output: 1294 --- </dd> </dl> </details> **Collect reviews on watched PRs and reviews that mention USER.** `Collector.reviews` runs only for USER’s open PRs. The inbox can therefore miss approvals, change requests, and review bodies on other watched PRs, including review-body mentions. The checkpoint then advances past those reviews. Add review collection for watched PRs and mentions on other PRs. Preserve the existing filters and avoid duplicate reports for USER’s PRs. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6b325417f41b2490597a9077 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/scripts/watch_inbox.py line 388 (outdated):

@@ -0,0 +1,502 @@
+#!/usr/bin/env python3
+"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue.
+
+Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the
+checkpoint (the time window start and the PR conditions already reported) from hidden
+markers in the inbox issue body, collects upstream comments, reviews and PR state changes
+since then, posts at most one comment and moves the checkpoint to the run start.
+
+Links use www.github.com (redirects to github.com): GitHub does not turn those into
+cross-references, so the upstream threads get no "mentioned this" timeline entries.
+"""
+
+import datetime as dt
+import json
+import os
+import re
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+API = "https://api.github.com"
+UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5")
+FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5")
+USER = os.environ.get("WATCH_USER", "Nawid3333")
+WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt")
+DRY_RUN = os.environ.get("DRY_RUN") == "1"
+
+INBOX_TITLE = "Watch inbox"
+INBOX_LABEL = "watch-inbox"
+FIRST_RUN_WINDOW = dt.timedelta(hours=6)
+MAX_WINDOW = dt.timedelta(days=3)
+# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet
+# listed by the API (clock skew, eventual consistency) is never skipped.
+SETTLE = dt.timedelta(seconds=60)
+MAX_SHOWN = 15
+MAX_LISTED = 200
+MERGE_CHECKS_PER_RUN = 8
+MIN_RATE_REMAINING = 100
+MAX_PAGES = 10
+FAILED = {"failure", "timed_out", "startup_failure"}
+
+SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->")
+STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->")
+MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE)
+
+
+class RateLow(Exception):
+    pass
+
+
+class Api:
+    def __init__(self, token):
+        self.token = token
+        self.calls = 0
+        self.remaining = None
+
+    def request(self, method, url, params=None, body=None):
+        if not url.startswith("https://"):
+            url = API + url
+        if params:
+            url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
+        if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING:
+            raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}")
+        data = json.dumps(body).encode() if body is not None else None
+        req = urllib.request.Request(url, data=data, method=method)
+        req.add_header("Accept", "application/vnd.github+json")
+        req.add_header("X-GitHub-Api-Version", "2022-11-28")
+        req.add_header("User-Agent", "watch-inbox")
+        req.add_header("Authorization", "Bearer " + self.token)
+        if data is not None:
+            req.add_header("Content-Type", "application/json")
+        for attempt in (1, 2):  # one retry for transient server and network errors
+            self.calls += 1
+            try:
+                with urllib.request.urlopen(req, timeout=60) as resp:
+                    headers = resp.headers
+                    raw = resp.read()
+                break
+            except urllib.error.HTTPError as err:
+                self._note_rate(err.headers)
+                if err.code >= 500 and attempt == 1:
+                    time.sleep(5)
+                    continue
+                detail = err.read().decode("utf-8", "replace")[:300]
+                raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None
+            except urllib.error.URLError:
+                if attempt == 2:
+                    raise
+                time.sleep(5)
+        self._note_rate(headers)
+        return (json.loads(raw) if raw else None), headers
+
+    def _note_rate(self, headers):
+        value = headers.get("X-RateLimit-Remaining") if headers else None
+        if value is not None:
+            self.remaining = int(value)
+
+    def get(self, path, params=None):
+        return self.request("GET", path, params)[0]
+
+    def pages(self, path, params):
+        url, query, page = path, dict(params, per_page=100), 0
+        while url and page < MAX_PAGES:
+            data, headers = self.request("GET", url, query)
+            yield from data
+            url, query, page = next_link(headers, "next"), None, page + 1
+        if url:
+            print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped")
+
+    def tail(self, path, pages=2):
+        """Items of the last `pages` pages of an ascending list, oldest first."""
+        data, headers = self.request("GET", path, {"per_page": 100})
+        last = next_link(headers, "last")
+        if not last:
+            return data
+        data, headers = self.request("GET", last)
+        if pages > 1 and next_link(headers, "prev"):
+            data = self.request("GET", next_link(headers, "prev"))[0] + data
+        return data
+
+
+def next_link(headers, rel):
+    for part in (headers.get("Link") or "").split(","):
+        match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part)
+        if match and match.group(2) == rel:
+            return match.group(1)
+    return None
+
+
+def parse_ts(text):
+    return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
+
+
+def iso(moment):
+    return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+GHOST = {"login": "ghost", "type": "User"}
+
+
+def same_user(login):
+    return (login or "").lower() == USER.lower()
+
+
+def is_bot(user):
+    return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]")
+
+
+def www(url):
+    return url.replace("https://github.com/", "https://www.github.com/", 1)
+
+
+def load_watch_list(path):
+    numbers = set()
+    try:
+        with open(path, encoding="utf-8") as handle:
+            for line in handle:
+                numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0]))
+    except FileNotFoundError:
+        print(f"::warning::{path} not found; watching only own threads and mentions")
+    return numbers
+
+
+# ---- text handling --------------------------------------------------------------------
+
+
+def strip_markup(body):
+    text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S)
+    previous = None
+    while previous != text:  # innermost <details> first, CodeRabbit nests them
+        previous = text
+        text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I)
+    text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text)  # images and badges
+    text = re.sub(r"\[\s*\]\([^)]*\)", " ", text)  # links left empty by that
+    text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S)  # code blocks
+    text = re.sub(r"<[^>]+>", " ", text)
+    return text
+
+
+def plain(line):
+    line = re.sub(r"^\s*#+\s*", "", line)
+    line = line.replace("**", "").replace("__", "")
+    line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line)
+    return line.strip(" -*|")
+
+
+def summary(body, bot):
+    lines = []
+    for line in strip_markup(body).splitlines():
+        line = line.strip()
+        if line.startswith(">"):
+            if not bot:
+                continue  # a human quoting earlier text
+            line = re.sub(r"^(>\s*)+", "", line)  # bots put their headline in a quote
+        line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip()
+        if line and not re.fullmatch(r"[-*_=|: ]+", line):
+            lines.append(line)
+    if not lines:
+        return ""
+    if not bot:
+        return " ".join(lines)
+    # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a
+    # bold title; reviews and summaries carry a bold headline in their first lines.
+    if "|" in lines[0] and len(lines) > 1:
+        return f"{plain(lines[0])} · {plain(lines[1])}"
+    for line in lines[:4]:
+        if re.fullmatch(r"\*\*[^*]+\*\*", line):
+            return plain(line)
+    first = plain(lines[0])
+    if len(first) < 40 and len(lines) > 1:
+        first = f"{first} · {plain(lines[1])}"
+    return first
+
+
+def safe(text, limit):
+    """One markdown line that mentions, links and references nobody."""
+    text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)  # markdown links: keep the text
+    text = re.sub(r"https?://\S+", "(link)", text)
+    text = " ".join(text.split())
+    if len(text) > limit:
+        text = text[: limit - 1].rstrip() + "…"
+    text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]")
+    text = text.replace("@", "@\u200b")
+    text = re.sub(r"#(?=\d)", "#\u200b", text)
+    return text
+
+
+# ---- inbox and checkpoint -------------------------------------------------------------
+
+
+def find_inbox(api):
+    def pick(issues):
+        found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i]
+        found.sort(key=lambda i: (i["state"] != "open", i["number"]))
+        return found[0] if found else None
+
+    inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"}))
+    if inbox is None:
+        inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"}))
+    if inbox is None and not DRY_RUN:
+        try:
+            api.request("POST", f"/repos/{FORK}/labels",
+                        body={"name": INBOX_LABEL, "color": "0e8a16",
+                              "description": "Fork-only upstream watch inbox"})
+        except RuntimeError as err:
+            if "HTTP 422" not in str(err):
+                raise
+        inbox = api.request("POST", f"/repos/{FORK}/issues", body={
+            "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0]
+        print(f"created inbox issue #{inbox['number']}")
+    return inbox
+
+
+def read_checkpoint(api, inbox, now):
+    body = (inbox or {}).get("body") or ""
+    since = SINCE_RE.search(body)
+    if since is None and inbox and inbox.get("comments"):
+        for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")):
+            if SINCE_RE.search(comment["body"] or ""):
+                body = comment["body"]
+                since = SINCE_RE.search(body)
+                break
+    if since is None:
+        return now - FIRST_RUN_WINDOW, set()
+    return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body))
+
+
+def markers(since, state):
+    lines = [f"<!-- state: {key} -->" for key in sorted(state)]
+    return "\n".join(lines + [f"<!-- watch-since: {since} -->"])
+
+
+def inbox_body(since, state, calls):
+    text = (
+        "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever "
+        f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in "
+        f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}."
+    )
+    if since:
+        text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls."
+        text += "\n\n" + markers(since, state)
+    return text
+
+
+# ---- collection -----------------------------------------------------------------------
+
+
+class Collector:
+    def __init__(self, api, since, until, watch):
+        self.api, self.since, self.until, self.watch = api, since, until, watch
+        self.threads = {}
+        self.events = []
+
+    def in_window(self, stamp):
+        return stamp is not None and self.since <= parse_ts(stamp) < self.until
+
+    def remember(self, item):
+        pr = item.get("pull_request") or {}
+        self.threads[item["number"]] = {
+            "title": item["title"],
+            "author": (item.get("user") or GHOST)["login"],
+            "open": item["state"] == "open",
+            "closed_at": item.get("closed_at"),
+            "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")),
+            "url": item["html_url"],
+        }
+
+    def thread(self, number):
+        if number not in self.threads:
+            self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}"))
+        return self.threads[number]
+
+    def wanted(self, number, body):
+        if number in self.watch or MENTION_RE.search(body or ""):
+            return True
+        info = self.thread(number)
+        return info["open"] and same_user(info["author"])
+
+    def add(self, number, stamp, kind, url, user=None, body=None):
+        self.thread(number)  # the title, for render()
+        bot = bool(user) and is_bot(user)
+        author = user["login"].removesuffix("[bot]") if user else ""
+        self.events.append({"n": number, "at": stamp, "kind": kind, "url": url,
+                            "author": author, "bot": bot,
+                            "text": summary(body, bot) if body is not None else ""})
+
+    def threads_since(self):
+        params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)}
+        for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params):
+            self.remember(item)
+
+    def comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["issue_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"])
+
+    def review_comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["pull_request_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                where = c["path"].rsplit("/", 1)[-1]
+                line = c.get("line") or c.get("original_line")
+                kind = f"inline {where}:{line}" if line else f"inline {where}"
+                self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"])
+
+    def closures(self):
+        for number, info in self.threads.items():
+            if self.in_window(info["closed_at"]) and not info["open"] \
+                    and (number in self.watch or same_user(info["author"])):
+                self.add(number, info["closed_at"], "merged" if info["merged"] else "closed",
+                         info["url"])
+
+    def own_prs(self, previous):
+        """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet."""
+        prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"})
+               if same_user(p["user"]["login"])]
+        prs.sort(key=lambda p: p["number"])
+        runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs",
+                            {"actor": USER, "per_page": 100})["workflow_runs"]
+        recent = self.since - dt.timedelta(hours=1)
+        rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN))
+        turn = int(self.until.timestamp() // 600) % rounds
+        state = set()
+        for index, pr in enumerate(prs):
+            number, sha = pr["number"], pr["head"]["sha"][:7]
+            self.threads.setdefault(number, {
+                "title": pr["title"], "author": pr["user"]["login"], "open": True,
+                "closed_at": None, "merged": False, "url": pr["html_url"]})
+            updated = parse_ts(pr["updated_at"])
+            if updated >= self.since:
+                self.reviews(number)
+            failed = self.failed_runs(runs, pr["head"]["sha"])
+            if updated >= recent:
+                status = self.api.get(f"/repos/{UPSTREAM}/commits/{pr['head']['sha']}/status")
+                if status["state"] in ("failure", "error"):
+                    failed += [s["context"] for s in status["statuses"]
+                               if s["state"] in ("failure", "error")]
+            elif f"#{number} checks-failed {sha}" in previous:
+                failed = failed or ["status"]

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/scripts/watch_inbox.py
nl -ba .github/scripts/watch_inbox.py | sed -n '1,110p;180,260p;320,465p;500,640p'
rg -n -F -e 'own_prs(' -e 'checks-failed' -e 'dirty' -e 'watch_inbox' -- .github/scripts .github/workflows || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 18927


Script executed:

nl -ba .github/scripts/watch_inbox.py | sed -n '256,319p;460,502p'
nl -ba .github/workflows/watch-inbox.yml | sed -n '1,100p'

Repository: KytyPS5/KytyPS5

Length of output: 6904


Periodically recheck failed-check state.

For an older PR with an unchanged head, a resolved failure can remain in previous. The retained key can suppress a later failure notification for the same head. Recheck commit statuses periodically, as for dirty.

Suggested fix

-            if updated >= recent:
+            if updated >= recent or index % rounds == turn:
**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806165) On `.github/scripts/watch_inbox.py` line 388 (outdated): ```diff @@ -0,0 +1,502 @@ +#!/usr/bin/env python3 +"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue. + +Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the +checkpoint (the time window start and the PR conditions already reported) from hidden +markers in the inbox issue body, collects upstream comments, reviews and PR state changes +since then, posts at most one comment and moves the checkpoint to the run start. + +Links use www.github.com (redirects to github.com): GitHub does not turn those into +cross-references, so the upstream threads get no "mentioned this" timeline entries. +""" + +import datetime as dt +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +API = "https://api.github.com" +UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5") +FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5") +USER = os.environ.get("WATCH_USER", "Nawid3333") +WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt") +DRY_RUN = os.environ.get("DRY_RUN") == "1" + +INBOX_TITLE = "Watch inbox" +INBOX_LABEL = "watch-inbox" +FIRST_RUN_WINDOW = dt.timedelta(hours=6) +MAX_WINDOW = dt.timedelta(days=3) +# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet +# listed by the API (clock skew, eventual consistency) is never skipped. +SETTLE = dt.timedelta(seconds=60) +MAX_SHOWN = 15 +MAX_LISTED = 200 +MERGE_CHECKS_PER_RUN = 8 +MIN_RATE_REMAINING = 100 +MAX_PAGES = 10 +FAILED = {"failure", "timed_out", "startup_failure"} + +SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->") +STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->") +MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE) + + +class RateLow(Exception): + pass + + +class Api: + def __init__(self, token): + self.token = token + self.calls = 0 + self.remaining = None + + def request(self, method, url, params=None, body=None): + if not url.startswith("https://"): + url = API + url + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING: + raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}") + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Accept", "application/vnd.github+json") + req.add_header("X-GitHub-Api-Version", "2022-11-28") + req.add_header("User-Agent", "watch-inbox") + req.add_header("Authorization", "Bearer " + self.token) + if data is not None: + req.add_header("Content-Type", "application/json") + for attempt in (1, 2): # one retry for transient server and network errors + self.calls += 1 + try: + with urllib.request.urlopen(req, timeout=60) as resp: + headers = resp.headers + raw = resp.read() + break + except urllib.error.HTTPError as err: + self._note_rate(err.headers) + if err.code >= 500 and attempt == 1: + time.sleep(5) + continue + detail = err.read().decode("utf-8", "replace")[:300] + raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None + except urllib.error.URLError: + if attempt == 2: + raise + time.sleep(5) + self._note_rate(headers) + return (json.loads(raw) if raw else None), headers + + def _note_rate(self, headers): + value = headers.get("X-RateLimit-Remaining") if headers else None + if value is not None: + self.remaining = int(value) + + def get(self, path, params=None): + return self.request("GET", path, params)[0] + + def pages(self, path, params): + url, query, page = path, dict(params, per_page=100), 0 + while url and page < MAX_PAGES: + data, headers = self.request("GET", url, query) + yield from data + url, query, page = next_link(headers, "next"), None, page + 1 + if url: + print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped") + + def tail(self, path, pages=2): + """Items of the last `pages` pages of an ascending list, oldest first.""" + data, headers = self.request("GET", path, {"per_page": 100}) + last = next_link(headers, "last") + if not last: + return data + data, headers = self.request("GET", last) + if pages > 1 and next_link(headers, "prev"): + data = self.request("GET", next_link(headers, "prev"))[0] + data + return data + + +def next_link(headers, rel): + for part in (headers.get("Link") or "").split(","): + match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part) + if match and match.group(2) == rel: + return match.group(1) + return None + + +def parse_ts(text): + return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc) + + +def iso(moment): + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + +GHOST = {"login": "ghost", "type": "User"} + + +def same_user(login): + return (login or "").lower() == USER.lower() + + +def is_bot(user): + return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]") + + +def www(url): + return url.replace("https://github.com/", "https://www.github.com/", 1) + + +def load_watch_list(path): + numbers = set() + try: + with open(path, encoding="utf-8") as handle: + for line in handle: + numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0])) + except FileNotFoundError: + print(f"::warning::{path} not found; watching only own threads and mentions") + return numbers + + +# ---- text handling -------------------------------------------------------------------- + + +def strip_markup(body): + text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S) + previous = None + while previous != text: # innermost <details> first, CodeRabbit nests them + previous = text + text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I) + text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text) # images and badges + text = re.sub(r"\[\s*\]\([^)]*\)", " ", text) # links left empty by that + text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S) # code blocks + text = re.sub(r"<[^>]+>", " ", text) + return text + + +def plain(line): + line = re.sub(r"^\s*#+\s*", "", line) + line = line.replace("**", "").replace("__", "") + line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line) + return line.strip(" -*|") + + +def summary(body, bot): + lines = [] + for line in strip_markup(body).splitlines(): + line = line.strip() + if line.startswith(">"): + if not bot: + continue # a human quoting earlier text + line = re.sub(r"^(>\s*)+", "", line) # bots put their headline in a quote + line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip() + if line and not re.fullmatch(r"[-*_=|: ]+", line): + lines.append(line) + if not lines: + return "" + if not bot: + return " ".join(lines) + # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a + # bold title; reviews and summaries carry a bold headline in their first lines. + if "|" in lines[0] and len(lines) > 1: + return f"{plain(lines[0])} · {plain(lines[1])}" + for line in lines[:4]: + if re.fullmatch(r"\*\*[^*]+\*\*", line): + return plain(line) + first = plain(lines[0]) + if len(first) < 40 and len(lines) > 1: + first = f"{first} · {plain(lines[1])}" + return first + + +def safe(text, limit): + """One markdown line that mentions, links and references nobody.""" + text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) # markdown links: keep the text + text = re.sub(r"https?://\S+", "(link)", text) + text = " ".join(text.split()) + if len(text) > limit: + text = text[: limit - 1].rstrip() + "…" + text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]") + text = text.replace("@", "@\u200b") + text = re.sub(r"#(?=\d)", "#\u200b", text) + return text + + +# ---- inbox and checkpoint ------------------------------------------------------------- + + +def find_inbox(api): + def pick(issues): + found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i] + found.sort(key=lambda i: (i["state"] != "open", i["number"])) + return found[0] if found else None + + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"})) + if inbox is None: + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"})) + if inbox is None and not DRY_RUN: + try: + api.request("POST", f"/repos/{FORK}/labels", + body={"name": INBOX_LABEL, "color": "0e8a16", + "description": "Fork-only upstream watch inbox"}) + except RuntimeError as err: + if "HTTP 422" not in str(err): + raise + inbox = api.request("POST", f"/repos/{FORK}/issues", body={ + "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0] + print(f"created inbox issue #{inbox['number']}") + return inbox + + +def read_checkpoint(api, inbox, now): + body = (inbox or {}).get("body") or "" + since = SINCE_RE.search(body) + if since is None and inbox and inbox.get("comments"): + for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")): + if SINCE_RE.search(comment["body"] or ""): + body = comment["body"] + since = SINCE_RE.search(body) + break + if since is None: + return now - FIRST_RUN_WINDOW, set() + return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body)) + + +def markers(since, state): + lines = [f"<!-- state: {key} -->" for key in sorted(state)] + return "\n".join(lines + [f"<!-- watch-since: {since} -->"]) + + +def inbox_body(since, state, calls): + text = ( + "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever " + f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in " + f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}." + ) + if since: + text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls." + text += "\n\n" + markers(since, state) + return text + + +# ---- collection ----------------------------------------------------------------------- + + +class Collector: + def __init__(self, api, since, until, watch): + self.api, self.since, self.until, self.watch = api, since, until, watch + self.threads = {} + self.events = [] + + def in_window(self, stamp): + return stamp is not None and self.since <= parse_ts(stamp) < self.until + + def remember(self, item): + pr = item.get("pull_request") or {} + self.threads[item["number"]] = { + "title": item["title"], + "author": (item.get("user") or GHOST)["login"], + "open": item["state"] == "open", + "closed_at": item.get("closed_at"), + "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")), + "url": item["html_url"], + } + + def thread(self, number): + if number not in self.threads: + self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}")) + return self.threads[number] + + def wanted(self, number, body): + if number in self.watch or MENTION_RE.search(body or ""): + return True + info = self.thread(number) + return info["open"] and same_user(info["author"]) + + def add(self, number, stamp, kind, url, user=None, body=None): + self.thread(number) # the title, for render() + bot = bool(user) and is_bot(user) + author = user["login"].removesuffix("[bot]") if user else "" + self.events.append({"n": number, "at": stamp, "kind": kind, "url": url, + "author": author, "bot": bot, + "text": summary(body, bot) if body is not None else ""}) + + def threads_since(self): + params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)} + for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params): + self.remember(item) + + def comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["issue_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"]) + + def review_comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["pull_request_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + where = c["path"].rsplit("/", 1)[-1] + line = c.get("line") or c.get("original_line") + kind = f"inline {where}:{line}" if line else f"inline {where}" + self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"]) + + def closures(self): + for number, info in self.threads.items(): + if self.in_window(info["closed_at"]) and not info["open"] \ + and (number in self.watch or same_user(info["author"])): + self.add(number, info["closed_at"], "merged" if info["merged"] else "closed", + info["url"]) + + def own_prs(self, previous): + """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet.""" + prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"}) + if same_user(p["user"]["login"])] + prs.sort(key=lambda p: p["number"]) + runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs", + {"actor": USER, "per_page": 100})["workflow_runs"] + recent = self.since - dt.timedelta(hours=1) + rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN)) + turn = int(self.until.timestamp() // 600) % rounds + state = set() + for index, pr in enumerate(prs): + number, sha = pr["number"], pr["head"]["sha"][:7] + self.threads.setdefault(number, { + "title": pr["title"], "author": pr["user"]["login"], "open": True, + "closed_at": None, "merged": False, "url": pr["html_url"]}) + updated = parse_ts(pr["updated_at"]) + if updated >= self.since: + self.reviews(number) + failed = self.failed_runs(runs, pr["head"]["sha"]) + if updated >= recent: + status = self.api.get(f"/repos/{UPSTREAM}/commits/{pr['head']['sha']}/status") + if status["state"] in ("failure", "error"): + failed += [s["context"] for s in status["statuses"] + if s["state"] in ("failure", "error")] + elif f"#{number} checks-failed {sha}" in previous: + failed = failed or ["status"] ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/scripts/watch_inbox.py nl -ba .github/scripts/watch_inbox.py | sed -n '1,110p;180,260p;320,465p;500,640p' rg -n -F -e 'own_prs(' -e 'checks-failed' -e 'dirty' -e 'watch_inbox' -- .github/scripts .github/workflows || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 18927 --- Script executed: ```bash nl -ba .github/scripts/watch_inbox.py | sed -n '256,319p;460,502p' nl -ba .github/workflows/watch-inbox.yml | sed -n '1,100p' ``` Repository: KytyPS5/KytyPS5 Length of output: 6904 --- </dd> </dl> </details> **Periodically recheck failed-check state.** For an older PR with an unchanged head, a resolved failure can remain in `previous`. The retained key can suppress a later failure notification for the same head. Recheck commit statuses periodically, as for `dirty`. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff - if updated >= recent: + if updated >= recent or index % rounds == turn: ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:57172508793caa3a163f4624 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/scripts/watch_inbox.py line 456 (outdated):

@@ -0,0 +1,502 @@
+#!/usr/bin/env python3
+"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue.
+
+Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the
+checkpoint (the time window start and the PR conditions already reported) from hidden
+markers in the inbox issue body, collects upstream comments, reviews and PR state changes
+since then, posts at most one comment and moves the checkpoint to the run start.
+
+Links use www.github.com (redirects to github.com): GitHub does not turn those into
+cross-references, so the upstream threads get no "mentioned this" timeline entries.
+"""
+
+import datetime as dt
+import json
+import os
+import re
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+API = "https://api.github.com"
+UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5")
+FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5")
+USER = os.environ.get("WATCH_USER", "Nawid3333")
+WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt")
+DRY_RUN = os.environ.get("DRY_RUN") == "1"
+
+INBOX_TITLE = "Watch inbox"
+INBOX_LABEL = "watch-inbox"
+FIRST_RUN_WINDOW = dt.timedelta(hours=6)
+MAX_WINDOW = dt.timedelta(days=3)
+# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet
+# listed by the API (clock skew, eventual consistency) is never skipped.
+SETTLE = dt.timedelta(seconds=60)
+MAX_SHOWN = 15
+MAX_LISTED = 200
+MERGE_CHECKS_PER_RUN = 8
+MIN_RATE_REMAINING = 100
+MAX_PAGES = 10
+FAILED = {"failure", "timed_out", "startup_failure"}
+
+SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->")
+STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->")
+MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE)
+
+
+class RateLow(Exception):
+    pass
+
+
+class Api:
+    def __init__(self, token):
+        self.token = token
+        self.calls = 0
+        self.remaining = None
+
+    def request(self, method, url, params=None, body=None):
+        if not url.startswith("https://"):
+            url = API + url
+        if params:
+            url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
+        if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING:
+            raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}")
+        data = json.dumps(body).encode() if body is not None else None
+        req = urllib.request.Request(url, data=data, method=method)
+        req.add_header("Accept", "application/vnd.github+json")
+        req.add_header("X-GitHub-Api-Version", "2022-11-28")
+        req.add_header("User-Agent", "watch-inbox")
+        req.add_header("Authorization", "Bearer " + self.token)
+        if data is not None:
+            req.add_header("Content-Type", "application/json")
+        for attempt in (1, 2):  # one retry for transient server and network errors
+            self.calls += 1
+            try:
+                with urllib.request.urlopen(req, timeout=60) as resp:
+                    headers = resp.headers
+                    raw = resp.read()
+                break
+            except urllib.error.HTTPError as err:
+                self._note_rate(err.headers)
+                if err.code >= 500 and attempt == 1:
+                    time.sleep(5)
+                    continue
+                detail = err.read().decode("utf-8", "replace")[:300]
+                raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None
+            except urllib.error.URLError:
+                if attempt == 2:
+                    raise
+                time.sleep(5)
+        self._note_rate(headers)
+        return (json.loads(raw) if raw else None), headers
+
+    def _note_rate(self, headers):
+        value = headers.get("X-RateLimit-Remaining") if headers else None
+        if value is not None:
+            self.remaining = int(value)
+
+    def get(self, path, params=None):
+        return self.request("GET", path, params)[0]
+
+    def pages(self, path, params):
+        url, query, page = path, dict(params, per_page=100), 0
+        while url and page < MAX_PAGES:
+            data, headers = self.request("GET", url, query)
+            yield from data
+            url, query, page = next_link(headers, "next"), None, page + 1
+        if url:
+            print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped")
+
+    def tail(self, path, pages=2):
+        """Items of the last `pages` pages of an ascending list, oldest first."""
+        data, headers = self.request("GET", path, {"per_page": 100})
+        last = next_link(headers, "last")
+        if not last:
+            return data
+        data, headers = self.request("GET", last)
+        if pages > 1 and next_link(headers, "prev"):
+            data = self.request("GET", next_link(headers, "prev"))[0] + data
+        return data
+
+
+def next_link(headers, rel):
+    for part in (headers.get("Link") or "").split(","):
+        match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part)
+        if match and match.group(2) == rel:
+            return match.group(1)
+    return None
+
+
+def parse_ts(text):
+    return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
+
+
+def iso(moment):
+    return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+GHOST = {"login": "ghost", "type": "User"}
+
+
+def same_user(login):
+    return (login or "").lower() == USER.lower()
+
+
+def is_bot(user):
+    return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]")
+
+
+def www(url):
+    return url.replace("https://github.com/", "https://www.github.com/", 1)
+
+
+def load_watch_list(path):
+    numbers = set()
+    try:
+        with open(path, encoding="utf-8") as handle:
+            for line in handle:
+                numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0]))
+    except FileNotFoundError:
+        print(f"::warning::{path} not found; watching only own threads and mentions")
+    return numbers
+
+
+# ---- text handling --------------------------------------------------------------------
+
+
+def strip_markup(body):
+    text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S)
+    previous = None
+    while previous != text:  # innermost <details> first, CodeRabbit nests them
+        previous = text
+        text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I)
+    text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text)  # images and badges
+    text = re.sub(r"\[\s*\]\([^)]*\)", " ", text)  # links left empty by that
+    text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S)  # code blocks
+    text = re.sub(r"<[^>]+>", " ", text)
+    return text
+
+
+def plain(line):
+    line = re.sub(r"^\s*#+\s*", "", line)
+    line = line.replace("**", "").replace("__", "")
+    line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line)
+    return line.strip(" -*|")
+
+
+def summary(body, bot):
+    lines = []
+    for line in strip_markup(body).splitlines():
+        line = line.strip()
+        if line.startswith(">"):
+            if not bot:
+                continue  # a human quoting earlier text
+            line = re.sub(r"^(>\s*)+", "", line)  # bots put their headline in a quote
+        line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip()
+        if line and not re.fullmatch(r"[-*_=|: ]+", line):
+            lines.append(line)
+    if not lines:
+        return ""
+    if not bot:
+        return " ".join(lines)
+    # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a
+    # bold title; reviews and summaries carry a bold headline in their first lines.
+    if "|" in lines[0] and len(lines) > 1:
+        return f"{plain(lines[0])} · {plain(lines[1])}"
+    for line in lines[:4]:
+        if re.fullmatch(r"\*\*[^*]+\*\*", line):
+            return plain(line)
+    first = plain(lines[0])
+    if len(first) < 40 and len(lines) > 1:
+        first = f"{first} · {plain(lines[1])}"
+    return first
+
+
+def safe(text, limit):
+    """One markdown line that mentions, links and references nobody."""
+    text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)  # markdown links: keep the text
+    text = re.sub(r"https?://\S+", "(link)", text)
+    text = " ".join(text.split())
+    if len(text) > limit:
+        text = text[: limit - 1].rstrip() + "…"
+    text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]")
+    text = text.replace("@", "@\u200b")
+    text = re.sub(r"#(?=\d)", "#\u200b", text)
+    return text
+
+
+# ---- inbox and checkpoint -------------------------------------------------------------
+
+
+def find_inbox(api):
+    def pick(issues):
+        found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i]
+        found.sort(key=lambda i: (i["state"] != "open", i["number"]))
+        return found[0] if found else None
+
+    inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"}))
+    if inbox is None:
+        inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"}))
+    if inbox is None and not DRY_RUN:
+        try:
+            api.request("POST", f"/repos/{FORK}/labels",
+                        body={"name": INBOX_LABEL, "color": "0e8a16",
+                              "description": "Fork-only upstream watch inbox"})
+        except RuntimeError as err:
+            if "HTTP 422" not in str(err):
+                raise
+        inbox = api.request("POST", f"/repos/{FORK}/issues", body={
+            "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0]
+        print(f"created inbox issue #{inbox['number']}")
+    return inbox
+
+
+def read_checkpoint(api, inbox, now):
+    body = (inbox or {}).get("body") or ""
+    since = SINCE_RE.search(body)
+    if since is None and inbox and inbox.get("comments"):
+        for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")):
+            if SINCE_RE.search(comment["body"] or ""):
+                body = comment["body"]
+                since = SINCE_RE.search(body)
+                break
+    if since is None:
+        return now - FIRST_RUN_WINDOW, set()
+    return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body))
+
+
+def markers(since, state):
+    lines = [f"<!-- state: {key} -->" for key in sorted(state)]
+    return "\n".join(lines + [f"<!-- watch-since: {since} -->"])
+
+
+def inbox_body(since, state, calls):
+    text = (
+        "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever "
+        f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in "
+        f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}."
+    )
+    if since:
+        text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls."
+        text += "\n\n" + markers(since, state)
+    return text
+
+
+# ---- collection -----------------------------------------------------------------------
+
+
+class Collector:
+    def __init__(self, api, since, until, watch):
+        self.api, self.since, self.until, self.watch = api, since, until, watch
+        self.threads = {}
+        self.events = []
+
+    def in_window(self, stamp):
+        return stamp is not None and self.since <= parse_ts(stamp) < self.until
+
+    def remember(self, item):
+        pr = item.get("pull_request") or {}
+        self.threads[item["number"]] = {
+            "title": item["title"],
+            "author": (item.get("user") or GHOST)["login"],
+            "open": item["state"] == "open",
+            "closed_at": item.get("closed_at"),
+            "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")),
+            "url": item["html_url"],
+        }
+
+    def thread(self, number):
+        if number not in self.threads:
+            self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}"))
+        return self.threads[number]
+
+    def wanted(self, number, body):
+        if number in self.watch or MENTION_RE.search(body or ""):
+            return True
+        info = self.thread(number)
+        return info["open"] and same_user(info["author"])
+
+    def add(self, number, stamp, kind, url, user=None, body=None):
+        self.thread(number)  # the title, for render()
+        bot = bool(user) and is_bot(user)
+        author = user["login"].removesuffix("[bot]") if user else ""
+        self.events.append({"n": number, "at": stamp, "kind": kind, "url": url,
+                            "author": author, "bot": bot,
+                            "text": summary(body, bot) if body is not None else ""})
+
+    def threads_since(self):
+        params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)}
+        for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params):
+            self.remember(item)
+
+    def comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["issue_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"])
+
+    def review_comments(self):
+        params = {"since": iso(self.since), "sort": "created", "direction": "asc"}
+        for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params):
+            c["user"] = c.get("user") or GHOST
+            number = int(c["pull_request_url"].rsplit("/", 1)[1])
+            if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \
+                    and self.wanted(number, c["body"]):
+                where = c["path"].rsplit("/", 1)[-1]
+                line = c.get("line") or c.get("original_line")
+                kind = f"inline {where}:{line}" if line else f"inline {where}"
+                self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"])
+
+    def closures(self):
+        for number, info in self.threads.items():
+            if self.in_window(info["closed_at"]) and not info["open"] \
+                    and (number in self.watch or same_user(info["author"])):
+                self.add(number, info["closed_at"], "merged" if info["merged"] else "closed",
+                         info["url"])
+
+    def own_prs(self, previous):
+        """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet."""
+        prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"})
+               if same_user(p["user"]["login"])]
+        prs.sort(key=lambda p: p["number"])
+        runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs",
+                            {"actor": USER, "per_page": 100})["workflow_runs"]
+        recent = self.since - dt.timedelta(hours=1)
+        rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN))
+        turn = int(self.until.timestamp() // 600) % rounds
+        state = set()
+        for index, pr in enumerate(prs):
+            number, sha = pr["number"], pr["head"]["sha"][:7]
+            self.threads.setdefault(number, {
+                "title": pr["title"], "author": pr["user"]["login"], "open": True,
+                "closed_at": None, "merged": False, "url": pr["html_url"]})
+            updated = parse_ts(pr["updated_at"])
+            if updated >= self.since:
+                self.reviews(number)
+            failed = self.failed_runs(runs, pr["head"]["sha"])
+            if updated >= recent:
+                status = self.api.get(f"/repos/{UPSTREAM}/commits/{pr['head']['sha']}/status")
+                if status["state"] in ("failure", "error"):
+                    failed += [s["context"] for s in status["statuses"]
+                               if s["state"] in ("failure", "error")]
+            elif f"#{number} checks-failed {sha}" in previous:
+                failed = failed or ["status"]
+            if failed:
+                key = f"#{number} checks-failed {sha}"
+                state.add(key)
+                if key not in previous:
+                    names = ", ".join(sorted(set(failed)))
+                    self.add(number, iso(self.until), f"checks failed ({names}), head {sha}",
+                             pr["html_url"] + "/checks")
+            key = f"#{number} dirty {sha}"
+            if updated >= recent or index % rounds == turn:
+                merge_state = self.api.get(f"/repos/{UPSTREAM}/pulls/{number}").get("mergeable_state")
+                dirty = merge_state == "dirty" or (merge_state in (None, "unknown") and key in previous)
+            else:
+                dirty = key in previous
+            if dirty:
+                state.add(key)
+                if key not in previous:
+                    self.add(number, iso(self.until), f"merge conflict with main, head {sha}",
+                             pr["html_url"])
+        return state
+
+    def failed_runs(self, runs, sha):
+        latest = {}
+        for run in runs:
+            if run["head_sha"] == sha and run["status"] == "completed":
+                if run["workflow_id"] not in latest or run["id"] > latest[run["workflow_id"]]["id"]:
+                    latest[run["workflow_id"]] = run
+        return [run["name"] for run in latest.values() if run["conclusion"] in FAILED]
+
+    def reviews(self, number):
+        for review in self.api.tail(f"/repos/{UPSTREAM}/pulls/{number}/reviews"):
+            body = review.get("body") or ""
+            review["user"] = review.get("user") or GHOST
+            if not self.in_window(review.get("submitted_at")) or same_user(review["user"]["login"]):
+                continue
+            if review["state"] == "COMMENTED" and not body.strip():
+                continue  # container of inline comments, those are reported one by one
+            kind = {"APPROVED": "review approved", "CHANGES_REQUESTED": "review changes requested",
+                    "DISMISSED": "review dismissed"}.get(review["state"], "review")
+            self.add(number, review["submitted_at"], kind, review["html_url"], review["user"], body)
+
+
+# ---- output ---------------------------------------------------------------------------
+
+
+def render(events, threads, since, until, state):
+    order = {}
+    for event in sorted(events, key=lambda e: e["at"]):
+        first = order.setdefault(event["n"], [1, event["at"]])
+        if not event["bot"]:
+            first[0] = 0  # threads with human comments or state changes come first
+    events = sorted(events, key=lambda e: (order[e["n"]], e["n"], e["at"]))
+    lines = []
+    for event in events[:MAX_LISTED]:
+        title = safe(threads[event["n"]]["title"], 50)
+        head = f"- #\u200b{event['n']} {title} —"
+        if event["author"]:
+            text = safe(event["text"], 160)
+            lines.append(f"{head} {event['author']} {event['kind']}: {text} [link]({www(event['url'])})")
+        else:
+            lines.append(f"{head} {event['kind']} [link]({www(event['url'])})")
+    span = f"{since.strftime('%m-%d %H:%M')}–{until.strftime('%H:%M')} UTC"
+    out = [f"**{len(events)} new** · {span}", ""] + lines[:MAX_SHOWN]
+    if len(lines) > MAX_SHOWN:
+        out += ["", f"<details><summary>{len(events) - MAX_SHOWN} more</summary>", ""]
+        out += lines[MAX_SHOWN:]
+        if len(events) > MAX_LISTED:
+            out.append(f"- … {len(events) - MAX_LISTED} not listed")
+        out += ["", "</details>"]

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

git diff --name-status 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/scripts/watch_inbox.py
nl -ba .github/scripts/watch_inbox.py | sed -n '1,520p'

Repository: KytyPS5/KytyPS5

Length of output: 25370


Web query:

GitHub issue comment maximum body length 65536 characters API 422 limit

Result:

Sources consulted:
- REST API endpoints for issue comments - GitHub Docs — https://docs.github.com/en/rest/issues/comments?apiVersion=2026-03-10
- Maximum length for the comment body in issues and PR · community · Discussion #27190 · GitHub — GitHub discussion 27190 in orgs/community (link omitted to avoid creating a cross-reference)
- GitHub API error when comment exceeds max limit of characters allowed · Issue #66 · docker/scout-action — GitHub issue 66 in docker/scout-action (link omitted to avoid creating a cross-reference)
- Safe Outputs MCP Gateway Specification | GitHub Agentic Workflows — https://github.github.com/gh-aw/reference/safe-outputs-specification/
- Safe Outputs MCP Gateway Specification | GitHub Agentic Workflows — https://github.github.com/gh-aw/specs/safe-outputs-specification/
- …and 20 more

Web query:

GitHub issue comment body 65536 characters 262144 bytes ASCII validation limit actual 2024

Result:

Sources consulted:
- Maximum length for the comment body in issues and PR · community · Discussion #27190 · GitHub — GitHub discussion 27190 in orgs/community (link omitted to avoid creating a cross-reference)
- github-limits/README.md at master · dead-claudia/github-limits · GitHub — https://github.com/dead-claudia/github-limits/blob/master/README.md
- Cannot create issue - Comment is too long (maximum is 65536 characters) · community · Discussion #41331 · GitHub — GitHub discussion 41331 in orgs/community (link omitted to avoid creating a cross-reference)
- Test the undocumented GitHub behaviors the design depends on · Issue #17 · sluiceway/sluiceway — GitHub issue 17 in sluiceway/sluiceway (link omitted to avoid creating a cross-reference)
- GitHub API error when comment exceeds max limit of characters allowed · Issue #66 · docker/scout-action — GitHub issue 66 in docker/scout-action (link omitted to avoid creating a cross-reference)
- …and 18 more

Web query:

GitHub REST combined commit status endpoint maximum number contexts statuses response pagination context limit

Result:

Sources consulted:
- REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses
- Using pagination in the REST API - GitHub Docs — https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api?apiVersion=2026-03-10
- REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28
- REST API endpoints for commit statuses - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/rest/commits/statuses?apiVersion=2026-03-10
- …and 16 more

Script executed:

nl -ba .github/workflows/watch-inbox.yml | sed -n '1,220p'
nl -ba .github/watch-threads.txt | sed -n '1,160p'

Repository: KytyPS5/KytyPS5

Length of output: 2600


Web query:

GitHub maximum file name length git tree component 255 characters repository review comment path maximum

Result:

Sources consulted:
- Available rules for rulesets - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets
- REST API endpoints for pull request reviews - GitHub Docs — https://docs.github.com/en/rest/pulls/reviews?session_ref=direct
- …and 62 more

Web query:

GitHub commit status context maximum length 100 characters combined status default 30 per_page

Result:

Sources consulted:
- REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2026-03-10
- REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses
- REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28&apiversion=2022-11-28
- REST API endpoints for commit statuses - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/rest/commits/statuses
- …and 5 more

Bound the posted comment size.

render can exceed GitHub’s issue-comment limit when many failed-check contexts are listed. A failed POST prevents the checkpoint update. If later runs remain oversized, older events can fall outside MAX_WINDOW.

Limit the complete rendered comment by UTF-8 size, including state markers. Report any omitted events.

Tools

Ruff (0.17.1)

[warning] 449-449: String contains ambiguous – (EN DASH). Did you mean - (HYPHEN-MINUS)?

(RUF001)


[warning] 450-450: Consider iterable unpacking instead of concatenation

Replace with iterable unpacking

(RUF005)

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806174) On `.github/scripts/watch_inbox.py` line 456 (outdated): ```diff @@ -0,0 +1,502 @@ +#!/usr/bin/env python3 +"""Fork-only: report new upstream activity that concerns WATCH_USER in the fork's "Watch inbox" issue. + +Run by .github/workflows/watch-inbox.yml. Standard library only. Each run reads the +checkpoint (the time window start and the PR conditions already reported) from hidden +markers in the inbox issue body, collects upstream comments, reviews and PR state changes +since then, posts at most one comment and moves the checkpoint to the run start. + +Links use www.github.com (redirects to github.com): GitHub does not turn those into +cross-references, so the upstream threads get no "mentioned this" timeline entries. +""" + +import datetime as dt +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +API = "https://api.github.com" +UPSTREAM = os.environ.get("UPSTREAM_REPO", "KytyPS5/KytyPS5") +FORK = os.environ.get("GITHUB_REPOSITORY", "Nawid3333/KytyPS5") +USER = os.environ.get("WATCH_USER", "Nawid3333") +WATCH_FILE = os.environ.get("WATCH_FILE", ".github/watch-threads.txt") +DRY_RUN = os.environ.get("DRY_RUN") == "1" + +INBOX_TITLE = "Watch inbox" +INBOX_LABEL = "watch-inbox" +FIRST_RUN_WINDOW = dt.timedelta(hours=6) +MAX_WINDOW = dt.timedelta(days=3) +# Events newer than "now - SETTLE" wait for the next run, so an event that is not yet +# listed by the API (clock skew, eventual consistency) is never skipped. +SETTLE = dt.timedelta(seconds=60) +MAX_SHOWN = 15 +MAX_LISTED = 200 +MERGE_CHECKS_PER_RUN = 8 +MIN_RATE_REMAINING = 100 +MAX_PAGES = 10 +FAILED = {"failure", "timed_out", "startup_failure"} + +SINCE_RE = re.compile(r"<!-- watch-since: (\S+) -->") +STATE_RE = re.compile(r"<!-- state: (#\d+ [a-z-]+ [0-9a-f]+) -->") +MENTION_RE = re.compile(r"@" + re.escape(USER) + r"\b", re.IGNORECASE) + + +class RateLow(Exception): + pass + + +class Api: + def __init__(self, token): + self.token = token + self.calls = 0 + self.remaining = None + + def request(self, method, url, params=None, body=None): + if not url.startswith("https://"): + url = API + url + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + if method == "GET" and self.remaining is not None and self.remaining < MIN_RATE_REMAINING: + raise RateLow(f"rate limit remaining {self.remaining} < {MIN_RATE_REMAINING}") + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Accept", "application/vnd.github+json") + req.add_header("X-GitHub-Api-Version", "2022-11-28") + req.add_header("User-Agent", "watch-inbox") + req.add_header("Authorization", "Bearer " + self.token) + if data is not None: + req.add_header("Content-Type", "application/json") + for attempt in (1, 2): # one retry for transient server and network errors + self.calls += 1 + try: + with urllib.request.urlopen(req, timeout=60) as resp: + headers = resp.headers + raw = resp.read() + break + except urllib.error.HTTPError as err: + self._note_rate(err.headers) + if err.code >= 500 and attempt == 1: + time.sleep(5) + continue + detail = err.read().decode("utf-8", "replace")[:300] + raise RuntimeError(f"{method} {url} -> HTTP {err.code}: {detail}") from None + except urllib.error.URLError: + if attempt == 2: + raise + time.sleep(5) + self._note_rate(headers) + return (json.loads(raw) if raw else None), headers + + def _note_rate(self, headers): + value = headers.get("X-RateLimit-Remaining") if headers else None + if value is not None: + self.remaining = int(value) + + def get(self, path, params=None): + return self.request("GET", path, params)[0] + + def pages(self, path, params): + url, query, page = path, dict(params, per_page=100), 0 + while url and page < MAX_PAGES: + data, headers = self.request("GET", url, query) + yield from data + url, query, page = next_link(headers, "next"), None, page + 1 + if url: + print(f"::warning::{path}: stopped after {MAX_PAGES} pages, later items skipped") + + def tail(self, path, pages=2): + """Items of the last `pages` pages of an ascending list, oldest first.""" + data, headers = self.request("GET", path, {"per_page": 100}) + last = next_link(headers, "last") + if not last: + return data + data, headers = self.request("GET", last) + if pages > 1 and next_link(headers, "prev"): + data = self.request("GET", next_link(headers, "prev"))[0] + data + return data + + +def next_link(headers, rel): + for part in (headers.get("Link") or "").split(","): + match = re.match(r'\s*<([^>]+)>;\s*rel="([^"]+)"', part) + if match and match.group(2) == rel: + return match.group(1) + return None + + +def parse_ts(text): + return dt.datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc) + + +def iso(moment): + return moment.strftime("%Y-%m-%dT%H:%M:%SZ") + + +GHOST = {"login": "ghost", "type": "User"} + + +def same_user(login): + return (login or "").lower() == USER.lower() + + +def is_bot(user): + return user.get("type") == "Bot" or user.get("login", "").endswith("[bot]") + + +def www(url): + return url.replace("https://github.com/", "https://www.github.com/", 1) + + +def load_watch_list(path): + numbers = set() + try: + with open(path, encoding="utf-8") as handle: + for line in handle: + numbers.update(int(n) for n in re.findall(r"\d+", line.split("#", 1)[0])) + except FileNotFoundError: + print(f"::warning::{path} not found; watching only own threads and mentions") + return numbers + + +# ---- text handling -------------------------------------------------------------------- + + +def strip_markup(body): + text = re.sub(r"<!--.*?-->", " ", body or "", flags=re.S) + previous = None + while previous != text: # innermost <details> first, CodeRabbit nests them + previous = text + text = re.sub(r"<details>(?:(?!<details>).)*?</details>", " ", text, flags=re.S | re.I) + text = re.sub(r"!\[[^\]]*\]\([^)]*\)", " ", text) # images and badges + text = re.sub(r"\[\s*\]\([^)]*\)", " ", text) # links left empty by that + text = re.sub(r"```.*?(```|$)", " ", text, flags=re.S) # code blocks + text = re.sub(r"<[^>]+>", " ", text) + return text + + +def plain(line): + line = re.sub(r"^\s*#+\s*", "", line) + line = line.replace("**", "").replace("__", "") + line = re.sub(r"(?<!\w)_(\S(?:.*?\S)?)_(?!\w)", r"\1", line) + return line.strip(" -*|") + + +def summary(body, bot): + lines = [] + for line in strip_markup(body).splitlines(): + line = line.strip() + if line.startswith(">"): + if not bot: + continue # a human quoting earlier text + line = re.sub(r"^(>\s*)+", "", line) # bots put their headline in a quote + line = re.sub(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]", "", line).strip() + if line and not re.fullmatch(r"[-*_=|: ]+", line): + lines.append(line) + if not lines: + return "" + if not bot: + return " ".join(lines) + # CodeRabbit: inline comments open with a tag line ("Potential issue | Major") and a + # bold title; reviews and summaries carry a bold headline in their first lines. + if "|" in lines[0] and len(lines) > 1: + return f"{plain(lines[0])} · {plain(lines[1])}" + for line in lines[:4]: + if re.fullmatch(r"\*\*[^*]+\*\*", line): + return plain(line) + first = plain(lines[0]) + if len(first) < 40 and len(lines) > 1: + first = f"{first} · {plain(lines[1])}" + return first + + +def safe(text, limit): + """One markdown line that mentions, links and references nobody.""" + text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text) # markdown links: keep the text + text = re.sub(r"https?://\S+", "(link)", text) + text = " ".join(text.split()) + if len(text) > limit: + text = text[: limit - 1].rstrip() + "…" + text = text.replace("<", "&lt;").replace(">", "&gt;").replace("[", "\\[").replace("]", "\\]") + text = text.replace("@", "@\u200b") + text = re.sub(r"#(?=\d)", "#\u200b", text) + return text + + +# ---- inbox and checkpoint ------------------------------------------------------------- + + +def find_inbox(api): + def pick(issues): + found = [i for i in issues if i["title"] == INBOX_TITLE and "pull_request" not in i] + found.sort(key=lambda i: (i["state"] != "open", i["number"])) + return found[0] if found else None + + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"labels": INBOX_LABEL, "state": "all"})) + if inbox is None: + inbox = pick(api.pages(f"/repos/{FORK}/issues", {"state": "all"})) + if inbox is None and not DRY_RUN: + try: + api.request("POST", f"/repos/{FORK}/labels", + body={"name": INBOX_LABEL, "color": "0e8a16", + "description": "Fork-only upstream watch inbox"}) + except RuntimeError as err: + if "HTTP 422" not in str(err): + raise + inbox = api.request("POST", f"/repos/{FORK}/issues", body={ + "title": INBOX_TITLE, "body": inbox_body("", [], 0), "labels": [INBOX_LABEL]})[0] + print(f"created inbox issue #{inbox['number']}") + return inbox + + +def read_checkpoint(api, inbox, now): + body = (inbox or {}).get("body") or "" + since = SINCE_RE.search(body) + if since is None and inbox and inbox.get("comments"): + for comment in reversed(api.tail(f"/repos/{FORK}/issues/{inbox['number']}/comments")): + if SINCE_RE.search(comment["body"] or ""): + body = comment["body"] + since = SINCE_RE.search(body) + break + if since is None: + return now - FIRST_RUN_WINDOW, set() + return max(parse_ts(since.group(1)), now - MAX_WINDOW), set(STATE_RE.findall(body)) + + +def markers(since, state): + lines = [f"<!-- state: {key} -->" for key in sorted(state)] + return "\n".join(lines + [f"<!-- watch-since: {since} -->"]) + + +def inbox_body(since, state, calls): + text = ( + "Fork-only. `.github/workflows/watch-inbox.yml` posts one comment here whenever " + f"{UPSTREAM} has new comments, reviews or PR state changes on threads listed in " + f"`.github/watch-threads.txt`, on {USER}'s open issues and PRs, or that mention {USER}." + ) + if since: + text += f"\n\nLast check: window up to {since.replace('T', ' ').rstrip('Z')} UTC, {calls} API calls." + text += "\n\n" + markers(since, state) + return text + + +# ---- collection ----------------------------------------------------------------------- + + +class Collector: + def __init__(self, api, since, until, watch): + self.api, self.since, self.until, self.watch = api, since, until, watch + self.threads = {} + self.events = [] + + def in_window(self, stamp): + return stamp is not None and self.since <= parse_ts(stamp) < self.until + + def remember(self, item): + pr = item.get("pull_request") or {} + self.threads[item["number"]] = { + "title": item["title"], + "author": (item.get("user") or GHOST)["login"], + "open": item["state"] == "open", + "closed_at": item.get("closed_at"), + "merged": bool(pr.get("merged_at")) or bool(item.get("merged_at")), + "url": item["html_url"], + } + + def thread(self, number): + if number not in self.threads: + self.remember(self.api.get(f"/repos/{UPSTREAM}/issues/{number}")) + return self.threads[number] + + def wanted(self, number, body): + if number in self.watch or MENTION_RE.search(body or ""): + return True + info = self.thread(number) + return info["open"] and same_user(info["author"]) + + def add(self, number, stamp, kind, url, user=None, body=None): + self.thread(number) # the title, for render() + bot = bool(user) and is_bot(user) + author = user["login"].removesuffix("[bot]") if user else "" + self.events.append({"n": number, "at": stamp, "kind": kind, "url": url, + "author": author, "bot": bot, + "text": summary(body, bot) if body is not None else ""}) + + def threads_since(self): + params = {"state": "all", "sort": "updated", "direction": "desc", "since": iso(self.since)} + for item in self.api.pages(f"/repos/{UPSTREAM}/issues", params): + self.remember(item) + + def comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/issues/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["issue_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + self.add(number, c["created_at"], "comment", c["html_url"], c["user"], c["body"]) + + def review_comments(self): + params = {"since": iso(self.since), "sort": "created", "direction": "asc"} + for c in self.api.pages(f"/repos/{UPSTREAM}/pulls/comments", params): + c["user"] = c.get("user") or GHOST + number = int(c["pull_request_url"].rsplit("/", 1)[1]) + if self.in_window(c["created_at"]) and not same_user(c["user"]["login"]) \ + and self.wanted(number, c["body"]): + where = c["path"].rsplit("/", 1)[-1] + line = c.get("line") or c.get("original_line") + kind = f"inline {where}:{line}" if line else f"inline {where}" + self.add(number, c["created_at"], kind, c["html_url"], c["user"], c["body"]) + + def closures(self): + for number, info in self.threads.items(): + if self.in_window(info["closed_at"]) and not info["open"] \ + and (number in self.watch or same_user(info["author"])): + self.add(number, info["closed_at"], "merged" if info["merged"] else "closed", + info["url"]) + + def own_prs(self, previous): + """Reviews on USER's open PRs, plus conflicts and failed checks not reported yet.""" + prs = [p for p in self.api.pages(f"/repos/{UPSTREAM}/pulls", {"state": "open"}) + if same_user(p["user"]["login"])] + prs.sort(key=lambda p: p["number"]) + runs = self.api.get(f"/repos/{UPSTREAM}/actions/runs", + {"actor": USER, "per_page": 100})["workflow_runs"] + recent = self.since - dt.timedelta(hours=1) + rounds = max(1, -(-len(prs) // MERGE_CHECKS_PER_RUN)) + turn = int(self.until.timestamp() // 600) % rounds + state = set() + for index, pr in enumerate(prs): + number, sha = pr["number"], pr["head"]["sha"][:7] + self.threads.setdefault(number, { + "title": pr["title"], "author": pr["user"]["login"], "open": True, + "closed_at": None, "merged": False, "url": pr["html_url"]}) + updated = parse_ts(pr["updated_at"]) + if updated >= self.since: + self.reviews(number) + failed = self.failed_runs(runs, pr["head"]["sha"]) + if updated >= recent: + status = self.api.get(f"/repos/{UPSTREAM}/commits/{pr['head']['sha']}/status") + if status["state"] in ("failure", "error"): + failed += [s["context"] for s in status["statuses"] + if s["state"] in ("failure", "error")] + elif f"#{number} checks-failed {sha}" in previous: + failed = failed or ["status"] + if failed: + key = f"#{number} checks-failed {sha}" + state.add(key) + if key not in previous: + names = ", ".join(sorted(set(failed))) + self.add(number, iso(self.until), f"checks failed ({names}), head {sha}", + pr["html_url"] + "/checks") + key = f"#{number} dirty {sha}" + if updated >= recent or index % rounds == turn: + merge_state = self.api.get(f"/repos/{UPSTREAM}/pulls/{number}").get("mergeable_state") + dirty = merge_state == "dirty" or (merge_state in (None, "unknown") and key in previous) + else: + dirty = key in previous + if dirty: + state.add(key) + if key not in previous: + self.add(number, iso(self.until), f"merge conflict with main, head {sha}", + pr["html_url"]) + return state + + def failed_runs(self, runs, sha): + latest = {} + for run in runs: + if run["head_sha"] == sha and run["status"] == "completed": + if run["workflow_id"] not in latest or run["id"] > latest[run["workflow_id"]]["id"]: + latest[run["workflow_id"]] = run + return [run["name"] for run in latest.values() if run["conclusion"] in FAILED] + + def reviews(self, number): + for review in self.api.tail(f"/repos/{UPSTREAM}/pulls/{number}/reviews"): + body = review.get("body") or "" + review["user"] = review.get("user") or GHOST + if not self.in_window(review.get("submitted_at")) or same_user(review["user"]["login"]): + continue + if review["state"] == "COMMENTED" and not body.strip(): + continue # container of inline comments, those are reported one by one + kind = {"APPROVED": "review approved", "CHANGES_REQUESTED": "review changes requested", + "DISMISSED": "review dismissed"}.get(review["state"], "review") + self.add(number, review["submitted_at"], kind, review["html_url"], review["user"], body) + + +# ---- output --------------------------------------------------------------------------- + + +def render(events, threads, since, until, state): + order = {} + for event in sorted(events, key=lambda e: e["at"]): + first = order.setdefault(event["n"], [1, event["at"]]) + if not event["bot"]: + first[0] = 0 # threads with human comments or state changes come first + events = sorted(events, key=lambda e: (order[e["n"]], e["n"], e["at"])) + lines = [] + for event in events[:MAX_LISTED]: + title = safe(threads[event["n"]]["title"], 50) + head = f"- #\u200b{event['n']} {title} —" + if event["author"]: + text = safe(event["text"], 160) + lines.append(f"{head} {event['author']} {event['kind']}: {text} [link]({www(event['url'])})") + else: + lines.append(f"{head} {event['kind']} [link]({www(event['url'])})") + span = f"{since.strftime('%m-%d %H:%M')}–{until.strftime('%H:%M')} UTC" + out = [f"**{len(events)} new** · {span}", ""] + lines[:MAX_SHOWN] + if len(lines) > MAX_SHOWN: + out += ["", f"<details><summary>{len(events) - MAX_SHOWN} more</summary>", ""] + out += lines[MAX_SHOWN:] + if len(events) > MAX_LISTED: + out.append(f"- … {len(events) - MAX_LISTED} not listed") + out += ["", "</details>"] ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff --name-status 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/scripts/watch_inbox.py nl -ba .github/scripts/watch_inbox.py | sed -n '1,520p' ``` Repository: KytyPS5/KytyPS5 Length of output: 25370 --- Web query: `GitHub issue comment maximum body length 65536 characters API 422 limit` Result: ``` Sources consulted: - REST API endpoints for issue comments - GitHub Docs — https://docs.github.com/en/rest/issues/comments?apiVersion=2026-03-10 - Maximum length for the comment body in issues and PR · community · Discussion #27190 · GitHub — GitHub discussion 27190 in orgs/community (link omitted to avoid creating a cross-reference) - GitHub API error when comment exceeds max limit of characters allowed · Issue #66 · docker/scout-action — GitHub issue 66 in docker/scout-action (link omitted to avoid creating a cross-reference) - Safe Outputs MCP Gateway Specification | GitHub Agentic Workflows — https://github.github.com/gh-aw/reference/safe-outputs-specification/ - Safe Outputs MCP Gateway Specification | GitHub Agentic Workflows — https://github.github.com/gh-aw/specs/safe-outputs-specification/ - …and 20 more ``` --- Web query: `GitHub issue comment body 65536 characters 262144 bytes ASCII validation limit actual 2024` Result: ``` Sources consulted: - Maximum length for the comment body in issues and PR · community · Discussion #27190 · GitHub — GitHub discussion 27190 in orgs/community (link omitted to avoid creating a cross-reference) - github-limits/README.md at master · dead-claudia/github-limits · GitHub — https://github.com/dead-claudia/github-limits/blob/master/README.md - Cannot create issue - Comment is too long (maximum is 65536 characters) · community · Discussion #41331 · GitHub — GitHub discussion 41331 in orgs/community (link omitted to avoid creating a cross-reference) - Test the undocumented GitHub behaviors the design depends on · Issue #17 · sluiceway/sluiceway — GitHub issue 17 in sluiceway/sluiceway (link omitted to avoid creating a cross-reference) - GitHub API error when comment exceeds max limit of characters allowed · Issue #66 · docker/scout-action — GitHub issue 66 in docker/scout-action (link omitted to avoid creating a cross-reference) - …and 18 more ``` --- Web query: `GitHub REST combined commit status endpoint maximum number contexts statuses response pagination context limit` Result: ``` Sources consulted: - REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses - Using pagination in the REST API - GitHub Docs — https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api?apiVersion=2026-03-10 - REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28 - REST API endpoints for commit statuses - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/rest/commits/statuses?apiVersion=2026-03-10 - …and 16 more ``` --- Script executed: ```bash nl -ba .github/workflows/watch-inbox.yml | sed -n '1,220p' nl -ba .github/watch-threads.txt | sed -n '1,160p' ``` Repository: KytyPS5/KytyPS5 Length of output: 2600 --- Web query: `GitHub maximum file name length git tree component 255 characters repository review comment path maximum` Result: ``` Sources consulted: - Available rules for rulesets - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets - REST API endpoints for pull request reviews - GitHub Docs — https://docs.github.com/en/rest/pulls/reviews?session_ref=direct - …and 62 more ``` --- Web query: `GitHub commit status context maximum length 100 characters combined status default 30 per_page` Result: ``` Sources consulted: - REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2026-03-10 - REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses - REST API endpoints for commit statuses - GitHub Docs — https://docs.github.com/en/rest/commits/statuses?apiVersion=2022-11-28&apiversion=2022-11-28 - REST API endpoints for commit statuses - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/rest/commits/statuses - …and 5 more ``` --- </dd> </dl> </details> **Bound the posted comment size.** `render` can exceed GitHub’s issue-comment limit when many failed-check contexts are listed. A failed POST prevents the checkpoint update. If later runs remain oversized, older events can fall outside `MAX_WINDOW`. Limit the complete rendered comment by UTF-8 size, including state markers. Report any omitted events. <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/wrench-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/wrench.svg" width="16" height="16" align="absmiddle" alt=""></picture> Tools</summary> <dl> <dd> <br> <details> <summary>Ruff (0.17.1)</summary> <dl> <dd> <br> [warning] 449-449: String contains ambiguous `–` (EN DASH). Did you mean `-` (HYPHEN-MINUS)? (RUF001) --- [warning] 450-450: Consider iterable unpacking instead of concatenation Replace with iterable unpacking (RUF005) </dd> </dl> </details> </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:939c3cc2415d6c812d94607f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/workflows/delete-closed-branches.yml line 42 (outdated):

@@ -0,0 +1,56 @@
+# Fork-only housekeeping: delete branches whose pull requests are all merged or closed.
+# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of
+# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an
+# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull
+# request page ("Restore branch"); the run log lists each deleted branch with its head SHA.
+name: Delete branches of closed pull requests
+
+on:
+  schedule:
+    - cron: "17 4 * * *"
+  workflow_dispatch:
+    inputs:
+      dry_run:
+        description: "Only list the branches that would be deleted"
+        type: boolean
+        default: true
+
+permissions:
+  contents: write
+  pull-requests: read
+
+jobs:
+  cleanup:
+    if: github.repository_owner == 'Nawid3333'
+    runs-on: ubuntu-latest
+    steps:
+      - name: Delete fork branches whose pull requests are all merged or closed
+        env:
+          GH_TOKEN: ${{ github.token }}
+          FORK: ${{ github.repository }}
+          UPSTREAM: KytyPS5/KytyPS5
+          OWNER: ${{ github.repository_owner }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }}
+        run: |
+          set -euo pipefail
+          default=$(gh api "repos/$FORK" --jq .default_branch)
+          gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv
+          : > prs.tsv
+          for repo in "$UPSTREAM" "$FORK"; do
+            gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \
+              --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv
+          done

Minor · Performance & Scalability · Quick win

Supported by static analysis

Script executed:

git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml .github/workflows/sync-upstream.yml
printf '\n--- workflow at reviewed head ---\n'
git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/delete-closed-branches.yml | nl -ba
printf '\n--- sync workflow at reviewed head ---\n'
git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/sync-upstream.yml | nl -ba

Repository: KytyPS5/KytyPS5

Length of output: 7999


Web query:

GitHub delete branch open pull request does pull request close automatically deleting head branch REST API

Result:

Sources consulted:
- Deleting and restoring branches in a pull request - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request?apiVersion=2022-11-28
- REST API endpoints for Git references - GitHub Docs — https://docs.github.com/en/rest/git/refs
- Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches
- Deleting and restoring branches in a pull request - GitHub Enterprise Server 3.20 Docs — https://docs.github.com/en/enterprise-server%403.20/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request
- REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls?apiVersion=2026-03-10
- …and 19 more

Web query:

GitHub REST API delete git reference branch open pull request automatically closes pull request git push delete head branch

Result:

Sources consulted:
- REST API endpoints for Git references - GitHub Docs — https://docs.github.com/en/rest/git/refs
- Deleting and restoring branches in a pull request - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request
- Managing branches within your repository - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/commit-changes/managing-branches-within-your-repository?source=post_page---------------------------
- Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches
- Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches?trk=public_post_comment-text
- …and 7 more

Recheck open pull requests before deletion.

If a pull request opens after the listing, prs.tsv can still show only closed pull requests. The scheduled run can then delete the branch and close the new pull request.

Recheck both repositories immediately before deletion to narrow the race. A concurrency group alone cannot prevent a user from opening a pull request.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806181) On `.github/workflows/delete-closed-branches.yml` line 42 (outdated): ```diff @@ -0,0 +1,56 @@ +# Fork-only housekeeping: delete branches whose pull requests are all merged or closed. +# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of +# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an +# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull +# request page ("Restore branch"); the run log lists each deleted branch with its head SHA. +name: Delete branches of closed pull requests + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + dry_run: + description: "Only list the branches that would be deleted" + type: boolean + default: true + +permissions: + contents: write + pull-requests: read + +jobs: + cleanup: + if: github.repository_owner == 'Nawid3333' + runs-on: ubuntu-latest + steps: + - name: Delete fork branches whose pull requests are all merged or closed + env: + GH_TOKEN: ${{ github.token }} + FORK: ${{ github.repository }} + UPSTREAM: KytyPS5/KytyPS5 + OWNER: ${{ github.repository_owner }} + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }} + run: | + set -euo pipefail + default=$(gh api "repos/$FORK" --jq .default_branch) + gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv + : > prs.tsv + for repo in "$UPSTREAM" "$FORK"; do + gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \ + --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv + done ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Performance & Scalability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml .github/workflows/sync-upstream.yml printf '\n--- workflow at reviewed head ---\n' git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/delete-closed-branches.yml | nl -ba printf '\n--- sync workflow at reviewed head ---\n' git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/sync-upstream.yml | nl -ba ``` Repository: KytyPS5/KytyPS5 Length of output: 7999 --- Web query: `GitHub delete branch open pull request does pull request close automatically deleting head branch REST API` Result: ``` Sources consulted: - Deleting and restoring branches in a pull request - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request?apiVersion=2022-11-28 - REST API endpoints for Git references - GitHub Docs — https://docs.github.com/en/rest/git/refs - Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches - Deleting and restoring branches in a pull request - GitHub Enterprise Server 3.20 Docs — https://docs.github.com/en/enterprise-server%403.20/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request - REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls?apiVersion=2026-03-10 - …and 19 more ``` --- Web query: `GitHub REST API delete git reference branch open pull request automatically closes pull request git push delete head branch` Result: ``` Sources consulted: - REST API endpoints for Git references - GitHub Docs — https://docs.github.com/en/rest/git/refs - Deleting and restoring branches in a pull request - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request - Managing branches within your repository - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/commit-changes/managing-branches-within-your-repository?source=post_page--------------------------- - Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches - Managing the automatic deletion of branches - GitHub Docs — https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-the-automatic-deletion-of-branches?trk=public_post_comment-text - …and 7 more ``` --- </dd> </dl> </details> **Recheck open pull requests before deletion.** If a pull request opens after the listing, `prs.tsv` can still show only closed pull requests. The scheduled run can then delete the branch and close the new pull request. Recheck both repositories immediately before deletion to narrow the race. A concurrency group alone cannot prevent a user from opening a pull request. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6be05768a176fbae8df01d56 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/workflows/delete-closed-branches.yml line 50 (outdated):

@@ -0,0 +1,56 @@
+# Fork-only housekeeping: delete branches whose pull requests are all merged or closed.
+# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of
+# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an
+# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull
+# request page ("Restore branch"); the run log lists each deleted branch with its head SHA.
+name: Delete branches of closed pull requests
+
+on:
+  schedule:
+    - cron: "17 4 * * *"
+  workflow_dispatch:
+    inputs:
+      dry_run:
+        description: "Only list the branches that would be deleted"
+        type: boolean
+        default: true
+
+permissions:
+  contents: write
+  pull-requests: read
+
+jobs:
+  cleanup:
+    if: github.repository_owner == 'Nawid3333'
+    runs-on: ubuntu-latest
+    steps:
+      - name: Delete fork branches whose pull requests are all merged or closed
+        env:
+          GH_TOKEN: ${{ github.token }}
+          FORK: ${{ github.repository }}
+          UPSTREAM: KytyPS5/KytyPS5
+          OWNER: ${{ github.repository_owner }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }}
+        run: |
+          set -euo pipefail
+          default=$(gh api "repos/$FORK" --jq .default_branch)
+          gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv
+          : > prs.tsv
+          for repo in "$UPSTREAM" "$FORK"; do
+            gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \
+              --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv
+          done
+          deleted=0
+          while IFS=$'\t' read -r branch sha; do
+            [ "$branch" = "$default" ] && continue
+            states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u)
+            [ -z "$states" ] && continue
+            grep -qx open <<<"$states" && continue
+            numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv)
+            echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged"

Major · Data Integrity & Integration · Heavy lift

Supported by static analysis

Script executed:

git cat-file -e 182161eb3e31439d97433607a8aa95463c56a9cc^{commit} && git cat-file -e 4ee58a2584a8205d36f42667240ba08b4a6d37c7^{commit} && git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml
printf '\n--- reviewed workflow ---\n'
git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/delete-closed-branches.yml | nl -ba

Repository: KytyPS5/KytyPS5

Length of output: 5903


Web query:

GitHub closed merged pull request head sha changes when pushing new commits to same branch after closing restore branch commits

Result:

Sources consulted:
- REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls
- Pull request merges - GitHub Docs — https://docs.github.com/en/pull-requests/reference/pull-request-merges
- REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls?apiVersion=2026-03-10
- Merging a pull request - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/merging-a-pull-request?ref=iwantaito
- Merging a pull request - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/merging-a-pull-request?tool=webui
- …and 30 more

Keep branches with work added after a PR closes.

If the owner pushes new commits after a PR closes, the scheduled run can delete the branch before a new PR opens. The new work is not protected by the closed PR. Check that the branch has no later work before deleting it.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806186) On `.github/workflows/delete-closed-branches.yml` line 50 (outdated): ```diff @@ -0,0 +1,56 @@ +# Fork-only housekeeping: delete branches whose pull requests are all merged or closed. +# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of +# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an +# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull +# request page ("Restore branch"); the run log lists each deleted branch with its head SHA. +name: Delete branches of closed pull requests + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + dry_run: + description: "Only list the branches that would be deleted" + type: boolean + default: true + +permissions: + contents: write + pull-requests: read + +jobs: + cleanup: + if: github.repository_owner == 'Nawid3333' + runs-on: ubuntu-latest + steps: + - name: Delete fork branches whose pull requests are all merged or closed + env: + GH_TOKEN: ${{ github.token }} + FORK: ${{ github.repository }} + UPSTREAM: KytyPS5/KytyPS5 + OWNER: ${{ github.repository_owner }} + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }} + run: | + set -euo pipefail + default=$(gh api "repos/$FORK" --jq .default_branch) + gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv + : > prs.tsv + for repo in "$UPSTREAM" "$FORK"; do + gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \ + --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv + done + deleted=0 + while IFS=$'\t' read -r branch sha; do + [ "$branch" = "$default" ] && continue + states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u) + [ -z "$states" ] && continue + grep -qx open <<<"$states" && continue + numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv) + echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged" ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git cat-file -e 182161eb3e31439d97433607a8aa95463c56a9cc^{commit} && git cat-file -e 4ee58a2584a8205d36f42667240ba08b4a6d37c7^{commit} && git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml printf '\n--- reviewed workflow ---\n' git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/delete-closed-branches.yml | nl -ba ``` Repository: KytyPS5/KytyPS5 Length of output: 5903 --- Web query: `GitHub closed merged pull request head sha changes when pushing new commits to same branch after closing restore branch commits` Result: ``` Sources consulted: - REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls - Pull request merges - GitHub Docs — https://docs.github.com/en/pull-requests/reference/pull-request-merges - REST API endpoints for pull requests - GitHub Docs — https://docs.github.com/en/rest/pulls/pulls?apiVersion=2026-03-10 - Merging a pull request - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/merging-a-pull-request?ref=iwantaito - Merging a pull request - GitHub Docs — https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/merging-a-pull-request?tool=webui - …and 30 more ``` --- </dd> </dl> </details> **Keep branches with work added after a PR closes.** If the owner pushes new commits after a PR closes, the scheduled run can delete the branch before a new PR opens. The new work is not protected by the closed PR. Check that the branch has no later work before deleting it. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3c964de5bd35978aa014818d --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/workflows/delete-closed-branches.yml line 52 (outdated):

@@ -0,0 +1,56 @@
+# Fork-only housekeeping: delete branches whose pull requests are all merged or closed.
+# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of
+# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an
+# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull
+# request page ("Restore branch"); the run log lists each deleted branch with its head SHA.
+name: Delete branches of closed pull requests
+
+on:
+  schedule:
+    - cron: "17 4 * * *"
+  workflow_dispatch:
+    inputs:
+      dry_run:
+        description: "Only list the branches that would be deleted"
+        type: boolean
+        default: true
+
+permissions:
+  contents: write
+  pull-requests: read
+
+jobs:
+  cleanup:
+    if: github.repository_owner == 'Nawid3333'
+    runs-on: ubuntu-latest
+    steps:
+      - name: Delete fork branches whose pull requests are all merged or closed
+        env:
+          GH_TOKEN: ${{ github.token }}
+          FORK: ${{ github.repository }}
+          UPSTREAM: KytyPS5/KytyPS5
+          OWNER: ${{ github.repository_owner }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }}
+        run: |
+          set -euo pipefail
+          default=$(gh api "repos/$FORK" --jq .default_branch)
+          gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv
+          : > prs.tsv
+          for repo in "$UPSTREAM" "$FORK"; do
+            gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \
+              --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv
+          done
+          deleted=0
+          while IFS=$'\t' read -r branch sha; do
+            [ "$branch" = "$default" ] && continue
+            states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u)
+            [ -z "$states" ] && continue
+            grep -qx open <<<"$states" && continue
+            numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv)
+            echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged"
+            if [ "$DRY_RUN" != "true" ]; then
+              gh api -X DELETE "repos/$FORK/git/refs/heads/$branch"

Major · Functional Correctness · Quick win

Supported by static analysis

Script executed:

git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml
printf '\n--- workflow ---\n'
nl -ba .github/workflows/delete-closed-branches.yml
printf '\n--- gh availability ---\n'
command -v gh || :
printf '\n--- local ref name validity ---\n'
for b in 'feature#one' 'feature%2Fone' 'feature/one'; do if git check-ref-format "refs/heads/$b"; then printf '%s valid\n' "$b"; else printf '%s invalid\n' "$b"; fi; done

Repository: KytyPS5/KytyPS5

Length of output: 6020


Web query:

GitHub CLI gh api endpoint path percent encoding # fragment source code GitHub CLI

Result:

Sources consulted:
- cli/pkg/cmd/api/api.go at trunk · cli/cli · GitHub — https://github.com/cli/cli/blob/trunk/pkg/cmd/api/api.go
- GitHub CLI | Take GitHub to the command line — https://cli.github.com/manual/gh_api
- …and 29 more

Script executed:

printf '%s\n' '--- installed gh version ---'
gh --version
printf '%s\n' '--- upstream gh api implementation ---'
python3 - <<'PY'
import urllib.request
url = 'https://raw.githubusercontent.com/cli/cli/trunk/pkg/cmd/api/api.go'
try:
    lines = urllib.request.urlopen(url, timeout=12).read().decode().splitlines()
    matches = [i for i,s in enumerate(lines) if any(t in s for t in ('func apiRun(', 'func httpRequest(', 'http.NewRequest', 'RequestPath', 'RESTPrefix'))]
    selected=set()
    for i in matches:
        selected.update(range(max(0,i-5), min(len(lines),i+12)))
    for i in sorted(selected):
        print(f'{i+1}: {lines[i]}')
except Exception as e:
    print(type(e).__name__, str(e))
PY
printf '%s\n' '--- public fork branch list ---'
curl -fsS --max-time 12 'https://api.github.com/repos/Nawid3333/KytyPS5/branches?per_page=100' | python3 -c 'import sys,json; x=json.load(sys.stdin); print("\n".join(b["name"] for b in x))' || :

Repository: KytyPS5/KytyPS5

Length of output: 4844


Web query:

GitHub documentation restrictions branch names cannot contain # percent valid Git reference names

Result:

Sources consulted:
- Dealing with special characters in branch and tag names - GitHub Docs — https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names
- Git - git-check-ref-format Documentation — https://git-scm.com/docs/git-check-ref-format.html
- git/Documentation/git-check-ref-format.adoc at master · git/git · GitHub — https://github.com/git/git/blob/master/Documentation/git-check-ref-format.adoc
- …and 8 more

Script executed:

python3 - <<'PY'
import urllib.request
root='https://raw.githubusercontent.com/cli/cli/v2.102.1/'
for path in ['pkg/cmd/api/api.go', 'pkg/cmd/api/http.go']:
    print('\n---', root+path, '---')
    try:
        lines=urllib.request.urlopen(root+path,timeout=15).read().decode().splitlines()
    except Exception as e:
        print(type(e).__name__, str(e))
        continue
    if path.endswith('/api.go'):
        spans=[(313,450)]
    else:
        spans=[(1,len(lines))]
    for a,b in spans:
        for i in range(a-1,min(b,len(lines))):
            print(f'{i+1}: {lines[i]}')
PY

Repository: KytyPS5/KytyPS5

Length of output: 9855


Script executed:

python3 - <<'PY'
import urllib.request
root='https://raw.githubusercontent.com/cli/cli/v2.102.1/pkg/cmd/api/'
for file in ['api.go','params.go']:
    print('---',root+file,'---')
    try:
        lines=urllib.request.urlopen(root+file,timeout=12).read().decode().splitlines()
        for i,l in enumerate(lines):
            if 'func fillPlaceholders(' in l:
                j=i
                depth=0
                while j < len(lines):
                    print(f'{j+1}: {lines[j]}')
                    depth+=lines[j].count('{')-lines[j].count('}')
                    j+=1
                    if depth==0: break
    except Exception as e:
        print(type(e).__name__, str(e))
PY
printf '\n--- read-only gh request with a fragment ---\n'
GH_TOKEN=example gh api --verbose -X GET 'repos/Nawid3333/KytyPS5/branches/main#example' 2>&1 | sed -n '1,22p' || :
printf '\n--- documented net/http request semantics ---\n'
go doc net/http.NewRequest 2>/dev/null || :

Repository: KytyPS5/KytyPS5

Length of output: 2825


Encode the branch name in the DELETE endpoint.

If an eligible branch contains #, gh api omits the fragment from the request path. This can delete a different branch, including one with an open pull request. Percent-encode the branch path segments before constructing the endpoint.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806193) On `.github/workflows/delete-closed-branches.yml` line 52 (outdated): ```diff @@ -0,0 +1,56 @@ +# Fork-only housekeeping: delete branches whose pull requests are all merged or closed. +# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of +# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an +# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull +# request page ("Restore branch"); the run log lists each deleted branch with its head SHA. +name: Delete branches of closed pull requests + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + dry_run: + description: "Only list the branches that would be deleted" + type: boolean + default: true + +permissions: + contents: write + pull-requests: read + +jobs: + cleanup: + if: github.repository_owner == 'Nawid3333' + runs-on: ubuntu-latest + steps: + - name: Delete fork branches whose pull requests are all merged or closed + env: + GH_TOKEN: ${{ github.token }} + FORK: ${{ github.repository }} + UPSTREAM: KytyPS5/KytyPS5 + OWNER: ${{ github.repository_owner }} + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }} + run: | + set -euo pipefail + default=$(gh api "repos/$FORK" --jq .default_branch) + gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv + : > prs.tsv + for repo in "$UPSTREAM" "$FORK"; do + gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \ + --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv + done + deleted=0 + while IFS=$'\t' read -r branch sha; do + [ "$branch" = "$default" ] && continue + states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u) + [ -z "$states" ] && continue + grep -qx open <<<"$states" && continue + numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv) + echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged" + if [ "$DRY_RUN" != "true" ]; then + gh api -X DELETE "repos/$FORK/git/refs/heads/$branch" ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml printf '\n--- workflow ---\n' nl -ba .github/workflows/delete-closed-branches.yml printf '\n--- gh availability ---\n' command -v gh || : printf '\n--- local ref name validity ---\n' for b in 'feature#one' 'feature%2Fone' 'feature/one'; do if git check-ref-format "refs/heads/$b"; then printf '%s valid\n' "$b"; else printf '%s invalid\n' "$b"; fi; done ``` Repository: KytyPS5/KytyPS5 Length of output: 6020 --- Web query: `GitHub CLI gh api endpoint path percent encoding # fragment source code GitHub CLI` Result: ``` Sources consulted: - cli/pkg/cmd/api/api.go at trunk · cli/cli · GitHub — https://github.com/cli/cli/blob/trunk/pkg/cmd/api/api.go - GitHub CLI | Take GitHub to the command line — https://cli.github.com/manual/gh_api - …and 29 more ``` --- Script executed: ```bash printf '%s\n' '--- installed gh version ---' gh --version printf '%s\n' '--- upstream gh api implementation ---' python3 - <<'PY' import urllib.request url = 'https://raw.githubusercontent.com/cli/cli/trunk/pkg/cmd/api/api.go' try: lines = urllib.request.urlopen(url, timeout=12).read().decode().splitlines() matches = [i for i,s in enumerate(lines) if any(t in s for t in ('func apiRun(', 'func httpRequest(', 'http.NewRequest', 'RequestPath', 'RESTPrefix'))] selected=set() for i in matches: selected.update(range(max(0,i-5), min(len(lines),i+12))) for i in sorted(selected): print(f'{i+1}: {lines[i]}') except Exception as e: print(type(e).__name__, str(e)) PY printf '%s\n' '--- public fork branch list ---' curl -fsS --max-time 12 'https://api.github.com/repos/Nawid3333/KytyPS5/branches?per_page=100' | python3 -c 'import sys,json; x=json.load(sys.stdin); print("\n".join(b["name"] for b in x))' || : ``` Repository: KytyPS5/KytyPS5 Length of output: 4844 --- Web query: `GitHub documentation restrictions branch names cannot contain # percent valid Git reference names` Result: ``` Sources consulted: - Dealing with special characters in branch and tag names - GitHub Docs — https://docs.github.com/en/get-started/using-git/dealing-with-special-characters-in-branch-and-tag-names - Git - git-check-ref-format Documentation — https://git-scm.com/docs/git-check-ref-format.html - git/Documentation/git-check-ref-format.adoc at master · git/git · GitHub — https://github.com/git/git/blob/master/Documentation/git-check-ref-format.adoc - …and 8 more ``` --- Script executed: ```bash python3 - <<'PY' import urllib.request root='https://raw.githubusercontent.com/cli/cli/v2.102.1/' for path in ['pkg/cmd/api/api.go', 'pkg/cmd/api/http.go']: print('\n---', root+path, '---') try: lines=urllib.request.urlopen(root+path,timeout=15).read().decode().splitlines() except Exception as e: print(type(e).__name__, str(e)) continue if path.endswith('/api.go'): spans=[(313,450)] else: spans=[(1,len(lines))] for a,b in spans: for i in range(a-1,min(b,len(lines))): print(f'{i+1}: {lines[i]}') PY ``` Repository: KytyPS5/KytyPS5 Length of output: 9855 --- Script executed: ```bash python3 - <<'PY' import urllib.request root='https://raw.githubusercontent.com/cli/cli/v2.102.1/pkg/cmd/api/' for file in ['api.go','params.go']: print('---',root+file,'---') try: lines=urllib.request.urlopen(root+file,timeout=12).read().decode().splitlines() for i,l in enumerate(lines): if 'func fillPlaceholders(' in l: j=i depth=0 while j < len(lines): print(f'{j+1}: {lines[j]}') depth+=lines[j].count('{')-lines[j].count('}') j+=1 if depth==0: break except Exception as e: print(type(e).__name__, str(e)) PY printf '\n--- read-only gh request with a fragment ---\n' GH_TOKEN=example gh api --verbose -X GET 'repos/Nawid3333/KytyPS5/branches/main#example' 2>&1 | sed -n '1,22p' || : printf '\n--- documented net/http request semantics ---\n' go doc net/http.NewRequest 2>/dev/null || : ``` Repository: KytyPS5/KytyPS5 Length of output: 2825 --- </dd> </dl> </details> **Encode the branch name in the DELETE endpoint.** If an eligible branch contains `#`, `gh api` omits the fragment from the request path. This can delete a different branch, including one with an open pull request. Percent-encode the branch path segments before constructing the endpoint. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1664e2c7bb907e13efe80d7f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/workflows/delete-closed-branches.yml line 53 (outdated):

@@ -0,0 +1,56 @@
+# Fork-only housekeeping: delete branches whose pull requests are all merged or closed.
+# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of
+# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an
+# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull
+# request page ("Restore branch"); the run log lists each deleted branch with its head SHA.
+name: Delete branches of closed pull requests
+
+on:
+  schedule:
+    - cron: "17 4 * * *"
+  workflow_dispatch:
+    inputs:
+      dry_run:
+        description: "Only list the branches that would be deleted"
+        type: boolean
+        default: true
+
+permissions:
+  contents: write
+  pull-requests: read
+
+jobs:
+  cleanup:
+    if: github.repository_owner == 'Nawid3333'
+    runs-on: ubuntu-latest
+    steps:
+      - name: Delete fork branches whose pull requests are all merged or closed
+        env:
+          GH_TOKEN: ${{ github.token }}
+          FORK: ${{ github.repository }}
+          UPSTREAM: KytyPS5/KytyPS5
+          OWNER: ${{ github.repository_owner }}
+          DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }}
+        run: |
+          set -euo pipefail
+          default=$(gh api "repos/$FORK" --jq .default_branch)
+          gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv
+          : > prs.tsv
+          for repo in "$UPSTREAM" "$FORK"; do
+            gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \
+              --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv
+          done
+          deleted=0
+          while IFS=$'\t' read -r branch sha; do
+            [ "$branch" = "$default" ] && continue
+            states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u)
+            [ -z "$states" ] && continue
+            grep -qx open <<<"$states" && continue
+            numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv)
+            echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged"
+            if [ "$DRY_RUN" != "true" ]; then
+              gh api -X DELETE "repos/$FORK/git/refs/heads/$branch"
+              deleted=$((deleted + 1))

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

set -eu
printf '%s\n' '--- diff ---'
git diff --no-ext-diff --unified=80 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml
printf '%s\n' '--- final workflow ---'
nl -ba .github/workflows/delete-closed-branches.yml

Repository: KytyPS5/KytyPS5

Length of output: 5912


Continue cleanup after a failed branch deletion.

If one gh api -X DELETE call fails, set -e skips all later branches. Log the failure and continue, then fail the run after the loop so the failure remains visible.

Suggested fix

           deleted=0
+          failed=0
           while IFS=$'\t' read -r branch sha; do
-              gh api -X DELETE "repos/$FORK/git/refs/heads/$branch"
-              deleted=$((deleted + 1))
+              if gh api -X DELETE "repos/$FORK/git/refs/heads/$branch"; then
+                deleted=$((deleted + 1))
+              else
+                echo "::warning::Failed to delete branch '$branch'"
+                failed=1
+              fi
           echo "deleted $deleted branch(es) (dry run: $DRY_RUN)"
+          exit "$failed"
**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806198) On `.github/workflows/delete-closed-branches.yml` line 53 (outdated): ```diff @@ -0,0 +1,56 @@ +# Fork-only housekeeping: delete branches whose pull requests are all merged or closed. +# A branch is deleted only if at least one pull request (upstream or this fork) has it as head branch and none of +# them is open; branches without a pull request and the default branch are kept. Deleting the head branch of an +# open pull request would close it, so open ones are never touched. A deleted branch can be restored from its pull +# request page ("Restore branch"); the run log lists each deleted branch with its head SHA. +name: Delete branches of closed pull requests + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + dry_run: + description: "Only list the branches that would be deleted" + type: boolean + default: true + +permissions: + contents: write + pull-requests: read + +jobs: + cleanup: + if: github.repository_owner == 'Nawid3333' + runs-on: ubuntu-latest + steps: + - name: Delete fork branches whose pull requests are all merged or closed + env: + GH_TOKEN: ${{ github.token }} + FORK: ${{ github.repository }} + UPSTREAM: KytyPS5/KytyPS5 + OWNER: ${{ github.repository_owner }} + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false }} + run: | + set -euo pipefail + default=$(gh api "repos/$FORK" --jq .default_branch) + gh api --paginate "repos/$FORK/branches?per_page=100" --jq '.[] | [.name, .commit.sha] | @tsv' > branches.tsv + : > prs.tsv + for repo in "$UPSTREAM" "$FORK"; do + gh api --paginate "repos/$repo/pulls?state=all&per_page=100" \ + --jq ".[] | select(.head.repo.owner.login == \"$OWNER\") | [.head.ref, .state, .number] | @tsv" >> prs.tsv + done + deleted=0 + while IFS=$'\t' read -r branch sha; do + [ "$branch" = "$default" ] && continue + states=$(awk -F'\t' -v b="$branch" '$1 == b {print $2}' prs.tsv | sort -u) + [ -z "$states" ] && continue + grep -qx open <<<"$states" && continue + numbers=$(awk -F'\t' -v b="$branch" '$1 == b {printf "#%s ", $3}' prs.tsv) + echo "delete $branch ($sha) - pull requests ${numbers}all closed or merged" + if [ "$DRY_RUN" != "true" ]; then + gh api -X DELETE "repos/$FORK/git/refs/heads/$branch" + deleted=$((deleted + 1)) ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash set -eu printf '%s\n' '--- diff ---' git diff --no-ext-diff --unified=80 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/delete-closed-branches.yml printf '%s\n' '--- final workflow ---' nl -ba .github/workflows/delete-closed-branches.yml ``` Repository: KytyPS5/KytyPS5 Length of output: 5912 --- </dd> </dl> </details> **Continue cleanup after a failed branch deletion.** If one `gh api -X DELETE` call fails, `set -e` skips all later branches. Log the failure and continue, then fail the run after the loop so the failure remains visible. <details> <summary>Suggested fix</summary> <dl> <dd> <br> ```diff deleted=0 + failed=0 while IFS=$'\t' read -r branch sha; do ``` ```diff - gh api -X DELETE "repos/$FORK/git/refs/heads/$branch" - deleted=$((deleted + 1)) + if gh api -X DELETE "repos/$FORK/git/refs/heads/$branch"; then + deleted=$((deleted + 1)) + else + echo "::warning::Failed to delete branch '$branch'" + failed=1 + fi ``` ```diff echo "deleted $deleted branch(es) (dry run: $DRY_RUN)" + exit "$failed" ``` </dd> </dl> </details> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:927b2a3f798222c956f4bca0 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original
On .github/workflows/sync-upstream.yml line 25 (outdated):

@@ -0,0 +1,28 @@
+# Fork-only: keeps Nawid3333/KytyPS5 main in step with KytyPS5/KytyPS5 main.
+# Uses GitHub's "Sync fork" API, which fast-forwards or merges and fails on conflicts
+# instead of overwriting the fork-only commits (this file and .github/pull.yml).
+name: Sync main with upstream
+
+on:
+  schedule:
+    - cron: "17 * * * *"
+  workflow_dispatch:
+
+permissions:
+  contents: write
+
+concurrency:
+  group: sync-upstream
+  cancel-in-progress: false
+
+jobs:
+  sync:
+    if: github.repository == 'Nawid3333/KytyPS5'
+    runs-on: ubuntu-latest
+    steps:
+      - name: Merge KytyPS5/KytyPS5 main into this fork's main
+        env:
+          GH_TOKEN: ${{ github.token }}

Major · Functional Correctness · Quick win

Supported by static analysis

Script executed:

git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/sync-upstream.yml .github/workflows/build.yml
printf '\n--- sync workflow ---\n'
nl -ba .github/workflows/sync-upstream.yml
printf '\n--- build workflow ---\n'
nl -ba .github/workflows/build.yml
printf '\n--- workflow trigger and sync references ---\n'
rg -n 'workflow_run|workflow_dispatch|schedule:|merge-upstream|Nawid3333/KytyPS5|push:' .github/workflows || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 26550


Web query:

GitHub Actions GITHUB_TOKEN REST API merge-upstream push event trigger workflow exceptions github token sync fork

Result:

Sources consulted:
- REST API endpoints for branches - GitHub Docs — https://docs.github.com/en/rest/branches/branches?from=20423
- GITHUB_TOKEN - GitHub Docs — https://docs.github.com/en/actions/concepts/security/github_token
- Triggering a workflow - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow?ref=code-garage.fr
- Events that trigger workflows - GitHub Docs — https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows?ref=playwrightsolutions.com
- …and 8 more

Script executed:

printf '%s\n' '--- reviewed revision workflow triggers ---'
git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/build.yml | sed -n '1,18p'
printf '%s\n' '--- checkout identity ---'
git rev-parse HEAD
printf '%s\n' '--- named fork workflow state ---'
python3 - <<'PY'
import json, urllib.request, urllib.error
urls = [
    'https://api.github.com/repos/Nawid3333/KytyPS5',
    'https://api.github.com/repos/Nawid3333/KytyPS5/actions/workflows/build.yml',
]
for url in urls:
    print('URL:', url)
    try:
        request = urllib.request.Request(url, headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'review-inspection'})
        with urllib.request.urlopen(request, timeout=10) as response:
            obj = json.load(response)
        print(json.dumps({key: obj.get(key) for key in ('full_name', 'default_branch', 'fork', 'name', 'path', 'state', 'updated_at')}, indent=2))
    except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
        print('REQUEST FAILED:', type(error).__name__, str(error))
PY

Repository: KytyPS5/KytyPS5

Length of output: 1323


Script executed:

python3 - <<'PY'
import base64, json, urllib.request, urllib.error
root = 'https://api.github.com/repos/Nawid3333/KytyPS5'
paths = [
    '/contents/.github/workflows/build.yml?ref=main',
    '/actions/workflows/build.yml/runs?branch=main&event=push&per_page=5',
]
for path in paths:
    url = root + path
    print('URL:', url)
    try:
        request = urllib.request.Request(url, headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'review-inspection'})
        with urllib.request.urlopen(request, timeout=10) as response:
            obj = json.load(response)
        if path.startswith('/contents/'):
            text = base64.b64decode(obj['content']).decode()
            for number, line in enumerate(text.splitlines()[:18], 1):
                print(f'{number:3}: {line}')
        else:
            print('total_count:', obj.get('total_count'))
            for run in obj.get('workflow_runs', []):
                print(json.dumps({key: run.get(key) for key in ('event', 'head_branch', 'head_sha', 'status', 'conclusion', 'created_at')}))
    except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError) as error:
        print('REQUEST FAILED:', type(error).__name__, str(error))
PY

Repository: KytyPS5/KytyPS5

Length of output: 1896


Run the fork build after a sync changes main.

The sync uses GITHUB_TOKEN, so it does not trigger the fork’s push build. New upstream code can remain without a fork build or test run. Dispatch build.yml explicitly after a sync changes main, or use a credential that can trigger push workflows.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806209) On `.github/workflows/sync-upstream.yml` line 25 (outdated): ```diff @@ -0,0 +1,28 @@ +# Fork-only: keeps Nawid3333/KytyPS5 main in step with KytyPS5/KytyPS5 main. +# Uses GitHub's "Sync fork" API, which fast-forwards or merges and fails on conflicts +# instead of overwriting the fork-only commits (this file and .github/pull.yml). +name: Sync main with upstream + +on: + schedule: + - cron: "17 * * * *" + workflow_dispatch: + +permissions: + contents: write + +concurrency: + group: sync-upstream + cancel-in-progress: false + +jobs: + sync: + if: github.repository == 'Nawid3333/KytyPS5' + runs-on: ubuntu-latest + steps: + - name: Merge KytyPS5/KytyPS5 main into this fork's main + env: + GH_TOKEN: ${{ github.token }} ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- .github/workflows/sync-upstream.yml .github/workflows/build.yml printf '\n--- sync workflow ---\n' nl -ba .github/workflows/sync-upstream.yml printf '\n--- build workflow ---\n' nl -ba .github/workflows/build.yml printf '\n--- workflow trigger and sync references ---\n' rg -n 'workflow_run|workflow_dispatch|schedule:|merge-upstream|Nawid3333/KytyPS5|push:' .github/workflows || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 26550 --- Web query: `GitHub Actions GITHUB_TOKEN REST API merge-upstream push event trigger workflow exceptions github token sync fork` Result: ``` Sources consulted: - REST API endpoints for branches - GitHub Docs — https://docs.github.com/en/rest/branches/branches?from=20423 - GITHUB_TOKEN - GitHub Docs — https://docs.github.com/en/actions/concepts/security/github_token - Triggering a workflow - GitHub Enterprise Cloud Docs — https://docs.github.com/en/enterprise-cloud%40latest/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow?ref=code-garage.fr - Events that trigger workflows - GitHub Docs — https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows?ref=playwrightsolutions.com - …and 8 more ``` --- Script executed: ```bash printf '%s\n' '--- reviewed revision workflow triggers ---' git show 4ee58a2584a8205d36f42667240ba08b4a6d37c7:.github/workflows/build.yml | sed -n '1,18p' printf '%s\n' '--- checkout identity ---' git rev-parse HEAD printf '%s\n' '--- named fork workflow state ---' python3 - <<'PY' import json, urllib.request, urllib.error urls = [ 'https://api.github.com/repos/Nawid3333/KytyPS5', 'https://api.github.com/repos/Nawid3333/KytyPS5/actions/workflows/build.yml', ] for url in urls: print('URL:', url) try: request = urllib.request.Request(url, headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'review-inspection'}) with urllib.request.urlopen(request, timeout=10) as response: obj = json.load(response) print(json.dumps({key: obj.get(key) for key in ('full_name', 'default_branch', 'fork', 'name', 'path', 'state', 'updated_at')}, indent=2)) except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error: print('REQUEST FAILED:', type(error).__name__, str(error)) PY ``` Repository: KytyPS5/KytyPS5 Length of output: 1323 --- Script executed: ```bash python3 - <<'PY' import base64, json, urllib.request, urllib.error root = 'https://api.github.com/repos/Nawid3333/KytyPS5' paths = [ '/contents/.github/workflows/build.yml?ref=main', '/actions/workflows/build.yml/runs?branch=main&event=push&per_page=5', ] for path in paths: url = root + path print('URL:', url) try: request = urllib.request.Request(url, headers={'Accept': 'application/vnd.github+json', 'User-Agent': 'review-inspection'}) with urllib.request.urlopen(request, timeout=10) as response: obj = json.load(response) if path.startswith('/contents/'): text = base64.b64decode(obj['content']).decode() for number, line in enumerate(text.splitlines()[:18], 1): print(f'{number:3}: {line}') else: print('total_count:', obj.get('total_count')) for run in obj.get('workflow_runs', []): print(json.dumps({key: run.get(key) for key in ('event', 'head_branch', 'head_sha', 'status', 'conclusion', 'created_at')})) except (urllib.error.URLError, TimeoutError, OSError, ValueError, KeyError) as error: print('REQUEST FAILED:', type(error).__name__, str(error)) PY ``` Repository: KytyPS5/KytyPS5 Length of output: 1896 --- </dd> </dl> </details> **Run the fork build after a sync changes `main`.** The sync uses `GITHUB_TOKEN`, so it does not trigger the fork’s push build. New upstream code can remain without a fork build or test run. Dispatch `build.yml` explicitly after a sync changes `main`, or use a credential that can trigger push workflows. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3279ef87c185a7bbd0b79a74 --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -899,0 +922,4 @@
return true;
};
}
SysFileSetRecoverableDestination(probe);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original · edited 2026-11-06 20:12 UTC

Major · Stability & Availability · Heavy lift

Supported by static analysis

Script executed:

#!/bin/bash
rg -nP -C3 '\bInstallGpuResources\s*\(' --type=cpp
rg -nP -C3 '\bMemory::Shutdown\s*\(|\bShutdown\s*\(\)' src/kernel src/libs --type=cpp | head -80

Repository: KytyPS5/KytyPS5

Length of output: 28003


Script executed:

rg -n -F -e 'SysFileSetRecoverableDestination' -e 'SysFileRecoverableDestination' -e 'g_memory_operation_mutex' -e 'KernelMunmap' -e 'HandleGpuFault' -e 'g_virtual_ranges.reset' -- src/common src/kernel src/graphics
rg -n -F -e 'Memory::Shutdown' -e 'Memory::Lifecycle' -e 'FileSystem::Lifecycle' -e 'ShutdownGpu' -- src tests/KernelFileSystemTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 7404


Script executed:

for spec in 'src/common/platform/sysLinuxFileIO.cpp:1:180' 'src/common/platform/sysWindowsFileIO.cpp:1:190' 'src/kernel/memory.cpp:750:820' 'src/kernel/memory.cpp:890:950' 'src/kernel/memory.cpp:1020:1055' 'src/kernel/memory.cpp:1990:2045' 'src/emulator.cpp:70:180'; do
  IFS=: read -r f a b <<< "$spec"
  echo "===== $f:$a-$b ====="
  nl -ba "$f" | sed -n "${a},${b}p"
done
rg -n -F -e 'class VirtualRanges' -e 'VirtualRanges::Query' -e 'KernelRead(' -e 'KernelPread(' -e 'HandleGpuFault(' -e 'subsystems.Shutdown' -- src

Repository: KytyPS5/KytyPS5

Length of output: 29856


Script executed:

for spec in 'src/kernel/memory.cpp:210:375' 'src/kernel/memory.cpp:1920:2007' 'src/kernel/fileSystem.cpp:620:705' 'src/kernel/fileSystem.cpp:760:830' 'src/loader/runtimeLinker.cpp:625:710' 'src/graphics/presentation/window/vulkanWindow.cpp:955:982'; do
  IFS=: read -r f a b <<< "$spec"
  echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p"
done
rg -n -F -e 'SysFileRead(' -e 'class File' -e 'VirtualRanges::' -e 'UnmapMemoryOwner(' -e 'UnmapGpuRange(' -e 'Shutdown()' -- src/common/file.cpp src/common/file.h src/kernel/memory.cpp src/libs/agc.cpp
git rev-parse HEAD
git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- src/kernel/memory.cpp src/common/platform/sysLinuxFileIO.cpp src/common/platform/sysWindowsFileIO.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24696


Script executed:

for spec in 'src/common/file.cpp:190:215' 'src/kernel/memory.cpp:80:112' 'src/libs/agc.cpp:70:90'; do IFS=: read -r f a b <<< "$spec"; echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p"; done
rg -n -F -e 'bool RenderContext::HandleFault' -e 'RenderContext::UnmapMemory' -e 'bool GuestAddressSpace::UnmapBacking' -e 'bool FlexibleMemory::Unmap' -e 'UnmapBacking(' -- src/graphics/host_gpu src/kernel

Repository: KytyPS5/KytyPS5

Length of output: 4521


Script executed:

for spec in 'src/graphics/host_gpu/renderer/renderContext.cpp:45:120' 'src/kernel/memoryAddressSpace.inc:680:750' 'src/kernel/memory.cpp:1480:1520'; do IFS=: read -r f a b <<< "$spec"; echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p"; done
rg -n -F -e 'HandleFault(' -e 'UnmapMemory(' -- src/graphics/host_gpu/regionManager.cpp src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/renderer/renderContext.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8833


Keep the destination mapped through the recovery copy.

KernelMunmap can remove the destination after the probe approves it but before SysFileRead copies into it. The GPU fault handler then cannot resolve the fault, and the process can crash. Protect the destination from unmapping for the full probe-and-copy operation.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806219) · edited 2026-11-06 20:12 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash #!/bin/bash rg -nP -C3 '\bInstallGpuResources\s*\(' --type=cpp rg -nP -C3 '\bMemory::Shutdown\s*\(|\bShutdown\s*\(\)' src/kernel src/libs --type=cpp | head -80 ``` Repository: KytyPS5/KytyPS5 Length of output: 28003 --- Script executed: ```bash rg -n -F -e 'SysFileSetRecoverableDestination' -e 'SysFileRecoverableDestination' -e 'g_memory_operation_mutex' -e 'KernelMunmap' -e 'HandleGpuFault' -e 'g_virtual_ranges.reset' -- src/common src/kernel src/graphics rg -n -F -e 'Memory::Shutdown' -e 'Memory::Lifecycle' -e 'FileSystem::Lifecycle' -e 'ShutdownGpu' -- src tests/KernelFileSystemTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 7404 --- Script executed: ```bash for spec in 'src/common/platform/sysLinuxFileIO.cpp:1:180' 'src/common/platform/sysWindowsFileIO.cpp:1:190' 'src/kernel/memory.cpp:750:820' 'src/kernel/memory.cpp:890:950' 'src/kernel/memory.cpp:1020:1055' 'src/kernel/memory.cpp:1990:2045' 'src/emulator.cpp:70:180'; do IFS=: read -r f a b <<< "$spec" echo "===== $f:$a-$b =====" nl -ba "$f" | sed -n "${a},${b}p" done rg -n -F -e 'class VirtualRanges' -e 'VirtualRanges::Query' -e 'KernelRead(' -e 'KernelPread(' -e 'HandleGpuFault(' -e 'subsystems.Shutdown' -- src ``` Repository: KytyPS5/KytyPS5 Length of output: 29856 --- Script executed: ```bash for spec in 'src/kernel/memory.cpp:210:375' 'src/kernel/memory.cpp:1920:2007' 'src/kernel/fileSystem.cpp:620:705' 'src/kernel/fileSystem.cpp:760:830' 'src/loader/runtimeLinker.cpp:625:710' 'src/graphics/presentation/window/vulkanWindow.cpp:955:982'; do IFS=: read -r f a b <<< "$spec" echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p" done rg -n -F -e 'SysFileRead(' -e 'class File' -e 'VirtualRanges::' -e 'UnmapMemoryOwner(' -e 'UnmapGpuRange(' -e 'Shutdown()' -- src/common/file.cpp src/common/file.h src/kernel/memory.cpp src/libs/agc.cpp git rev-parse HEAD git diff --stat 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- src/kernel/memory.cpp src/common/platform/sysLinuxFileIO.cpp src/common/platform/sysWindowsFileIO.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24696 --- Script executed: ```bash for spec in 'src/common/file.cpp:190:215' 'src/kernel/memory.cpp:80:112' 'src/libs/agc.cpp:70:90'; do IFS=: read -r f a b <<< "$spec"; echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p"; done rg -n -F -e 'bool RenderContext::HandleFault' -e 'RenderContext::UnmapMemory' -e 'bool GuestAddressSpace::UnmapBacking' -e 'bool FlexibleMemory::Unmap' -e 'UnmapBacking(' -- src/graphics/host_gpu src/kernel ``` Repository: KytyPS5/KytyPS5 Length of output: 4521 --- Script executed: ```bash for spec in 'src/graphics/host_gpu/renderer/renderContext.cpp:45:120' 'src/kernel/memoryAddressSpace.inc:680:750' 'src/kernel/memory.cpp:1480:1520'; do IFS=: read -r f a b <<< "$spec"; echo "===== $f:$a-$b ====="; nl -ba "$f" | sed -n "${a},${b}p"; done rg -n -F -e 'HandleFault(' -e 'UnmapMemory(' -- src/graphics/host_gpu/regionManager.cpp src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/renderer/renderContext.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8833 --- </dd> </dl> </details> **Keep the destination mapped through the recovery copy.** `KernelMunmap` can remove the destination after the probe approves it but before `SysFileRead` copies into it. The GPU fault handler then cannot resolve the fault, and the process can crash. Protect the destination from unmapping for the full probe-and-copy operation. <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:faa6bce255be5e2024d6682c --> <!-- This is an auto-generated reply by CodeRabbit -->
@ -5514,0 +5537,4 @@
&prot_wrote);
Require(name, "protected-read fixture size",
prot_wrote == sizeof(prot_payload),
"the protected-read fixture file was not written");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original · edited 2026-11-06 20:12 UTC

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- tests/ShaderRecompilerComputeTests.cpp
rg -n -F -e 'Require(' -e 'kyty-protread-cache.bin' -e 'InstallGpuResources(' -- tests/ShaderRecompilerComputeTests.cpp
nl -ba tests/ShaderRecompilerComputeTests.cpp | sed -n '5400,5595p'
rg -n -F -e 'void Require(' -e 'bool Require(' -e 'prot_read_file' -- tests/ShaderRecompilerComputeTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 41569


Script executed:

nl -ba tests/ShaderRecompilerComputeTests.cpp | sed -n '1030,1095p;4455,4515p;5514,5584p'
rg -n -F -e 'class File' -e 'File::Create(' -e 'File::Write(' -e 'File::Read(' -e 'File::Seek(' -e 'File::~File' -- src/common
rg -n -F -e 'CheckDirtyBufferGarbageCollection(' -e 'catch (' -e 'int main(' -- tests/ShaderRecompilerComputeTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 11157


Script executed:

nl -ba src/common/file.h | sed -n '1,130p'
nl -ba src/common/file.cpp | sed -n '1,250p'
rg -n -F -e 'FileCreate(' -e 'FileSeek(' -e 'FileRead(' -e 'FileWrite(' -- src/common

Repository: KytyPS5/KytyPS5

Length of output: 11904


Script executed:

nl -ba src/common/platform/sysLinuxFileIO.cpp | sed -n '35,125p;155,185p'
nl -ba src/common/platform/sysWindowsFileIO.cpp | sed -n '35,130p;165,195p'

Repository: KytyPS5/KytyPS5

Length of output: 9638


Use a unique temporary fixture per test process.

On Linux, a second run can truncate the shared fixture before the first run reads it. The first run can then fail its byte-count assertion. An assertion failure also leaves the fixture behind. Create a unique fixture for each process and remove it after the test.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4496806233) · edited 2026-11-06 20:12 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash git diff 182161eb3e31439d97433607a8aa95463c56a9cc 4ee58a2584a8205d36f42667240ba08b4a6d37c7 -- tests/ShaderRecompilerComputeTests.cpp rg -n -F -e 'Require(' -e 'kyty-protread-cache.bin' -e 'InstallGpuResources(' -- tests/ShaderRecompilerComputeTests.cpp nl -ba tests/ShaderRecompilerComputeTests.cpp | sed -n '5400,5595p' rg -n -F -e 'void Require(' -e 'bool Require(' -e 'prot_read_file' -- tests/ShaderRecompilerComputeTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 41569 --- Script executed: ```bash nl -ba tests/ShaderRecompilerComputeTests.cpp | sed -n '1030,1095p;4455,4515p;5514,5584p' rg -n -F -e 'class File' -e 'File::Create(' -e 'File::Write(' -e 'File::Read(' -e 'File::Seek(' -e 'File::~File' -- src/common rg -n -F -e 'CheckDirtyBufferGarbageCollection(' -e 'catch (' -e 'int main(' -- tests/ShaderRecompilerComputeTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 11157 --- Script executed: ```bash nl -ba src/common/file.h | sed -n '1,130p' nl -ba src/common/file.cpp | sed -n '1,250p' rg -n -F -e 'FileCreate(' -e 'FileSeek(' -e 'FileRead(' -e 'FileWrite(' -- src/common ``` Repository: KytyPS5/KytyPS5 Length of output: 11904 --- Script executed: ```bash nl -ba src/common/platform/sysLinuxFileIO.cpp | sed -n '35,125p;155,185p' nl -ba src/common/platform/sysWindowsFileIO.cpp | sed -n '35,130p;165,195p' ``` Repository: KytyPS5/KytyPS5 Length of output: 9638 --- </dd> </dl> </details> **Use a unique temporary fixture per test process.** On Linux, a second run can truncate the shared fixture before the first run reads it. The first run can then fail its byte-count assertion. An assertion failure also leaves the fixture behind. Create a unique fixture for each process and remove it after the test. <!-- fingerprinting:phantom:poseidon:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:1efd12342efaf9ab141ddc37 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 19:41 UTC · original · reviewed

Actionable comments posted: 10

Nitpick comments: 1

tests/KernelFileSystemTests.cpp: 1

945-949: Trivial · Functional Correctness · Quick win

Test the production probe’s rejection and span walk.

The no-access tests use a range-only callback, not the production probe. The compute test exercises the production probe only on a CPU-writable mapping.

Add production-probe tests for a non-writable range and for a chunk that spans writable and non-writable ranges. The probe should reject these chunks before memcpy.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 182161eb3e and 4ee58a2584a8205d36f42667240ba08b4a6d37c7.

Files selected for processing: 13

  • .github/.gitignore
  • .github/pull.yml
  • .github/scripts/watch_inbox.py
  • .github/watch-threads.txt
  • .github/workflows/delete-closed-branches.yml
  • .github/workflows/sync-upstream.yml
  • .github/workflows/watch-inbox.yml
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/memory.cpp
  • tests/KernelFileSystemTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#pullrequestreview-5805972121) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 10** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/KernelFileSystemTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `945-949`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Functional Correctness** · **Quick win** **Test the production probe’s rejection and span walk.** The no-access tests use a range-only callback, not the production probe. The compute test exercises the production probe only on a CPU-writable mapping. Add production-probe tests for a non-writable range and for a chunk that spans writable and non-writable ranges. The probe should reject these chunks before `memcpy`. <!-- cr-comment:v1:208da5e6fbb62ad31cb8b98c --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/182161eb3e31439d97433607a8aa95463c56a9cc/.coderabbit.yaml>) - **Commit**: [182161e](<https://github.com/KytyPS5/KytyPS5/commit/182161eb3e31439d97433607a8aa95463c56a9cc>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `fc4d52fd-5f2b-4be4-933f-65fe2ecd17f2` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 182161eb3e31439d97433607a8aa95463c56a9cc and 4ee58a2584a8205d36f42667240ba08b4a6d37c7. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 13</summary> <dl> <dd> <br> * `.github/.gitignore` * `.github/pull.yml` * `.github/scripts/watch_inbox.py` * `.github/watch-threads.txt` * `.github/workflows/delete-closed-branches.yml` * `.github/workflows/sync-upstream.yml` * `.github/workflows/watch-inbox.yml` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/memory.cpp` * `tests/KernelFileSystemTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=6dc970e1-4a79-43e3-a00e-d77fb1055cd4 attempt=9856ea81-3152-4cfe-9cee-a2761f4a85f5 batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 20:08 UTC · original

Sorry for the noise: my first push of this branch was cut from my fork's main, so the PR briefly showed about 110 fork-only merge commits and my fork's .github files (sync and inbox workflows). That was a mistake. The branch now holds only the fix (76a84cc51 on top of 182161eb3), and CodeRabbit's comments on .github/... refer to those files and no longer apply.

I set the PR to draft while I push one test follow-up from the review (a unique file name for the protected-read fixture) and recheck it; I will mark it ready again after that.

**@⁠Nawid3333** on GitHub · 2026-11-06 20:08 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#issuecomment-6694344352) Sorry for the noise: my first push of this branch was cut from my fork's `main`, so the PR briefly showed about 110 fork-only merge commits and my fork's `.github` files (sync and inbox workflows). That was a mistake. The branch now holds only the fix (76a84cc51 on top of 182161eb3), and CodeRabbit's comments on `.github/...` refer to those files and no longer apply. I set the PR to draft while I push one test follow-up from the review (a unique file name for the protected-read fixture) and recheck it; I will mark it ready again after that.
@ -899,0 +922,4 @@
return true;
};
}
SysFileSetRecoverableDestination(probe);
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 20:12 UTC · original

The recovery copy is the guest's own store into its own buffer: a guest thread that unmaps a buffer while another of its threads is still reading a file into it would fault the same way on main with any CPU store into that buffer. Keeping the destination mapped would need a lock against KernelMunmap across file I/O for a use-after-free in the game; the probe stays a permission check, as the PR text says.

**@⁠Nawid3333** on GitHub · 2026-11-06 20:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497097453) The recovery copy is the guest's own store into its own buffer: a guest thread that unmaps a buffer while another of its threads is still reading a file into it would fault the same way on main with any CPU store into that buffer. Keeping the destination mapped would need a lock against `KernelMunmap` across file I/O for a use-after-free in the game; the probe stays a permission check, as the PR text says.
@ -5514,0 +5537,4 @@
&prot_wrote);
Require(name, "protected-read fixture size",
prot_wrote == sizeof(prot_payload),
"the protected-read fixture file was not written");
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 20:12 UTC · original

Fixed in 549d3630a: the fixture file name now carries a steady_clock count, like the other temporary files in this test (kyty_pm4_nop_dump_{}, kyty_shader_store_{}), so parallel runs do not share it.

**@⁠Nawid3333** on GitHub · 2026-11-06 20:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497098055) Fixed in 549d3630a: the fixture file name now carries a `steady_clock` count, like the other temporary files in this test (`kyty_pm4_nop_dump_{}`, `kyty_shader_store_{}`), so parallel runs do not share it.
@ -899,0 +922,4 @@
return true;
};
}
SysFileSetRecoverableDestination(probe);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 20:12 UTC · original

@⁠Nawid3333 Thanks for clarifying the intended contract. The probe checks permissions; it does not guarantee the buffer’s lifetime. If the guest unmaps the buffer during the read, the recovery copy can fault.

I withdraw the request to keep the destination mapped through the copy.

Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 20:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497103061) <!-- coderabbit-ai-generated:v1 --> @⁠Nawid3333 Thanks for clarifying the intended contract. The probe checks permissions; it does not guarantee the buffer’s lifetime. If the guest unmaps the buffer during the read, the recovery copy can fault. I withdraw the request to keep the destination mapped through the copy. <!-- <review_comment_withdrawn> --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -5514,0 +5537,4 @@
&prot_wrote);
Require(name, "protected-read fixture size",
prot_wrote == sizeof(prot_payload),
"the protected-read fixture file was not written");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 20:13 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Current revision ---'
git rev-parse HEAD
printf '%s\n' '--- Fixture references ---'
rg -n -C 8 'kyty.protread.cache|prot_read_path|prot_read_file|protected-read fixture' tests/ShaderRecompilerComputeTests.cpp
printf '%s\n' '--- Require implementation references ---'
rg -n -C 8 '\bRequire\s*\(' tests/ShaderRecompilerComputeTests.cpp | head -n 110
printf '%s\n' '--- Reported commit diff ---'
git show --format=fuller --no-ext-diff --stat 549d3630a -- tests/ShaderRecompilerComputeTests.cpp
git show --format= --no-ext-diff 549d3630a -- tests/ShaderRecompilerComputeTests.cpp
printf '%s\n' '--- File creation and destruction references ---'
rg -n -C 4 'File::~File|File::Create\(' src/common/file.cpp
rg -n -C 5 'SysFileCreate\(' src/common/platform/sysLinuxFileIO.cpp src/common/platform/sysWindowsFileIO.cpp

Length of output: 13828


@Nawid3333 Thanks for the update. The timestamp reduces the collision risk, but two processes can still get the same count. File creation would then truncate the existing fixture.

A failed Require also calls std::abort() before the removal code runs. Please use exclusive fixture creation with a retry on collision, and arrange cleanup before an assertion aborts.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497107834) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Current revision ---' git rev-parse HEAD printf '%s\n' '--- Fixture references ---' rg -n -C 8 'kyty.protread.cache|prot_read_path|prot_read_file|protected-read fixture' tests/ShaderRecompilerComputeTests.cpp printf '%s\n' '--- Require implementation references ---' rg -n -C 8 '\bRequire\s*\(' tests/ShaderRecompilerComputeTests.cpp | head -n 110 printf '%s\n' '--- Reported commit diff ---' git show --format=fuller --no-ext-diff --stat 549d3630a -- tests/ShaderRecompilerComputeTests.cpp git show --format= --no-ext-diff 549d3630a -- tests/ShaderRecompilerComputeTests.cpp printf '%s\n' '--- File creation and destruction references ---' rg -n -C 4 'File::~File|File::Create\(' src/common/file.cpp rg -n -C 5 'SysFileCreate\(' src/common/platform/sysLinuxFileIO.cpp src/common/platform/sysWindowsFileIO.cpp ``` Length of output: 13828 --- </dd> </dl> </details> `@Nawid3333` Thanks for the update. The timestamp reduces the collision risk, but two processes can still get the same count. File creation would then truncate the existing fixture. A failed `Require` also calls `std::abort()` before the removal code runs. Please use exclusive fixture creation with a retry on collision, and arrange cleanup before an assertion aborts. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=CodeRabbit%20caught%20a%20flaky-test%20race%3A%20use%20a%20unique%20temp%20fixture%20per%20process%20to%20prevent%20parallel%20runs%20from%20truncating%20it.%20Try%20%40coderabbitai%20for%20sharper%20code%20reviews%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2141%23discussion_r4496806233)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -5514,0 +5537,4 @@
&prot_wrote);
Require(name, "protected-read fixture size",
prot_wrote == sizeof(prot_payload),
"the protected-read fixture file was not written");
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 20:13 UTC · original

The fixture now follows the other temporary files in this test: kyty_pm4_nop_dump_{} uses the same steady_clock name, the same Common::File::Create and the same std::filesystem::remove after its checks. Two processes collide only if both read the same clock tick at this line, and a file left behind by an aborted run has a name no later run uses. I'm keeping it as it is rather than adding a retry loop for this one test.

**@⁠Nawid3333** on GitHub · 2026-11-06 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497114577) The fixture now follows the other temporary files in this test: `kyty_pm4_nop_dump_{}` uses the same `steady_clock` name, the same `Common::File::Create` and the same `std::filesystem::remove` after its checks. Two processes collide only if both read the same clock tick at this line, and a file left behind by an aborted run has a name no later run uses. I'm keeping it as it is rather than adding a retry loop for this one test.
@ -5514,0 +5537,4 @@
&prot_wrote);
Require(name, "protected-read fixture size",
prot_wrote == sizeof(prot_payload),
"the protected-read fixture file was not written");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 20:14 UTC · original

@⁠Nawid3333 Understood. The fixture follows the existing test pattern, and you’ve accepted the remaining collision risk. Thanks for explaining.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 20:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#discussion_r4497116763) <!-- coderabbit-ai-generated:v1 --> @⁠Nawid3333 Understood. The fixture follows the existing test pattern, and you’ve accepted the remaining collision risk. Thanks for explaining. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 20:58 UTC · original · reviewed

Nitpick comments: 1

tests/ShaderRecompilerComputeTests.cpp: 1

5550-5570: Trivial · Functional Correctness · Heavy lift

Test the kernel read with GPU-watched memory.

Add a KernelRead or KernelPread case that checks the guest bytes and GPU cache state. The direct Common::File::Read test skips the kernel caller’s pre-read invalidation, so it can miss regressions in that integration.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 76a84cc511 and 549d3630a0.

Files selected for processing: 2

  • tests/KernelFileSystemTests.cpp
  • tests/ShaderRecompilerComputeTests.cpp
Files skipped from review as they are similar to previous changes: 1

  • tests/KernelFileSystemTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 20:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#pullrequestreview-5806892485) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/brush-cleaning.svg" width="16" height="16" align="absmiddle" alt=""></picture> Nitpick comments: 1</summary><blockquote> <dl> <dd> <br> <details> <summary>tests/ShaderRecompilerComputeTests.cpp: 1</summary><blockquote> <dl> <dd> <br> `5550-5570`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/neutral-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Trivial** · **Functional Correctness** · **Heavy lift** **Test the kernel read with GPU-watched memory.** Add a `KernelRead` or `KernelPread` case that checks the guest bytes and GPU cache state. The direct `Common::File::Read` test skips the kernel caller’s pre-read invalidation, so it can miss regressions in that integration. <!-- cr-comment:v1:faf135bf784e6df8ae75c932 --> </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/182161eb3e31439d97433607a8aa95463c56a9cc/.coderabbit.yaml>) - **Commit**: [182161e](<https://github.com/KytyPS5/KytyPS5/commit/182161eb3e31439d97433607a8aa95463c56a9cc>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `08684e30-4e6c-467b-a3fd-0b26529597b5` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 76a84cc511958d049ed950231437bd167d96bc67 and 549d3630a06aad88419b2564a5af64655efd36b2. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `tests/KernelFileSystemTests.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-similar-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-similar.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files skipped from review as they are similar to previous changes: 1</summary> <dl> <dd> <br> * tests/KernelFileSystemTests.cpp </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=9ef1d068-3c3f-43dd-b922-40b34320993c attempt=c8e7fd94-9a34-48c4-ae91-b79519d6cd6f batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-06 23:15 UTC · original

@⁠coderabbitai Your nitpick from the last review (test the kernel read with GPU-watched memory) is in 4b8336a1f. The protected-read case now also reads the fixture through KernelPread, twice:

  • into a fully GPU-mapped range, where the pre-read invalidation unprotects the pages (the normal path);
  • into a range whose first page is not GPU-mapped, where the invalidation skips the range, so the recovery has to deliver the bytes.

Each read starts from a cleared destination and checks the guest bytes, the CPU ownership and the next buffer lookup. On my PC (Windows 11, RX 9070 XT), --buffer-cache-gc-only passes with this PR; with the PR's src reverted to 182161eb3 it fails at kernel-read bytes: KernelPread lost protected guest bytes.

The same commit drops the last fseeko of the Linux recovery: after the loop the stream is already at start + w, so that seek did nothing.

**@⁠Nawid3333** on GitHub · 2026-11-06 23:15 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#issuecomment-6698196507) @⁠coderabbitai Your nitpick from the last review (test the kernel read with GPU-watched memory) is in 4b8336a1f. The protected-read case now also reads the fixture through `KernelPread`, twice: - into a fully GPU-mapped range, where the pre-read invalidation unprotects the pages (the normal path); - into a range whose first page is not GPU-mapped, where the invalidation skips the range, so the recovery has to deliver the bytes. Each read starts from a cleared destination and checks the guest bytes, the CPU ownership and the next buffer lookup. On my PC (Windows 11, RX 9070 XT), `--buffer-cache-gc-only` passes with this PR; with the PR's `src` reverted to 182161eb3 it fails at `kernel-read bytes: KernelPread lost protected guest bytes`. The same commit drops the last `fseeko` of the Linux recovery: after the loop the stream is already at `start + w`, so that seek did nothing.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-06 23:16 UTC · original

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
printf '%s\n' '--- Current revision ---'
git rev-parse HEAD
printf '%s\n' '--- Follow-up commit summary ---'
git show --format=fuller --stat 4b8336a1f
printf '%s\n' '--- Source outlines ---'
ast-grep outline tests/ShaderRecompilerComputeTests.cpp --match 'BufferCacheDirtyGarbageCollection|KernelPread' --view expanded
ast-grep outline src/common/platform/sysLinuxFileIO.cpp --match 'SysFileRead' --view expanded
printf '%s\n' '--- Follow-up diff ---'
git show --format=medium 4b8336a1f -- tests/ShaderRecompilerComputeTests.cpp src/common/platform/sysLinuxFileIO.cpp
printf '%s\n' '--- Current kernel-read test context ---'
rg -n -C 14 'kernel-read bytes|KernelPread\(' tests/ShaderRecompilerComputeTests.cpp
printf '%s\n' '--- Current Linux recovery context ---'
rg -n -A 100 -B 10 'SysFileRead\(' src/common/platform/sysLinuxFileIO.cpp

Length of output: 14176


@Nawid3333 Thanks for the follow-up. I checked commit 4b8336a1f. The new KernelPread cases cover both mapping layouts and check the guest bytes, CPU ownership, and the next buffer lookup.

For successful recovery reads, the Linux loop advances the stream and w by the same amount. Removing the final seek looks consistent with that behavior.

I did not run the tests.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-06 23:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2141#issuecomment-6698213826) <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated reply by CodeRabbit --> > [!TIP] > For best results, initiate chat on the files or code changes. <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash printf '%s\n' '--- Current revision ---' git rev-parse HEAD printf '%s\n' '--- Follow-up commit summary ---' git show --format=fuller --stat 4b8336a1f printf '%s\n' '--- Source outlines ---' ast-grep outline tests/ShaderRecompilerComputeTests.cpp --match 'BufferCacheDirtyGarbageCollection|KernelPread' --view expanded ast-grep outline src/common/platform/sysLinuxFileIO.cpp --match 'SysFileRead' --view expanded printf '%s\n' '--- Follow-up diff ---' git show --format=medium 4b8336a1f -- tests/ShaderRecompilerComputeTests.cpp src/common/platform/sysLinuxFileIO.cpp printf '%s\n' '--- Current kernel-read test context ---' rg -n -C 14 'kernel-read bytes|KernelPread\(' tests/ShaderRecompilerComputeTests.cpp printf '%s\n' '--- Current Linux recovery context ---' rg -n -A 100 -B 10 'SysFileRead\(' src/common/platform/sysLinuxFileIO.cpp ``` Length of output: 14176 --- </dd> </dl> </details> `@Nawid3333` Thanks for the follow-up. I checked commit `4b8336a1f`. The new `KernelPread` cases cover both mapping layouts and check the guest bytes, CPU ownership, and the next buffer lookup. For successful recovery reads, the Linux loop advances the stream and `w` by the same amount. Removing the final seek looks consistent with that behavior. I did not run the tests. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=KernelPread%20now%20tests%20protected%20reads%20on%20GPU-mapped%20and%20unmapped%20ranges%2C%20checking%20guest%20bytes%2C%20CPU%20ownership%2C%20and%20cache%20lookup%20to%20catch%20regressions.%20Try%20%40coderabbitai%20for%20actionable%20code%20reviews!%20%F0%9F%9A%80&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2141)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub>
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2141/head:github-bot/gh-2141'
git switch 'github-bot/gh-2141'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2141'
git switch 'github-bot/gh-2141'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2141'
git switch 'github-bot/gh-2141'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2141'
git switch 'main'
git merge --squash 'github-bot/gh-2141'
git switch 'main'
git merge --ff-only 'github-bot/gh-2141'
git switch 'main'
git merge 'github-bot/gh-2141'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.