Skip to content

fix: prevent fork loop and JSON hang in keybinds hint - #1826

Open
snakeice wants to merge 2 commits into
HyDE-Project:devfrom
snakeice:fix/keybinds-hint-fork-loop-and-json-hang
Open

fix: prevent fork loop and JSON hang in keybinds hint#1826
snakeice wants to merge 2 commits into
HyDE-Project:devfrom
snakeice:fix/keybinds-hint-fork-loop-and-json-hang

Conversation

@snakeice

@snakeice snakeice commented Jul 23, 2026

Copy link
Copy Markdown

Problem

Two bugs in the keybinds hint system were causing system-wide performance degradation (fork storms with ~568 forks/s, load average spikes to 100+).

Bug 1: keybinds_hint.sh — infinite self-re-execution (exec $0)

The script uses exec $0 in two places as a fallback when rofi produces no output or when a dispatch fails. This causes the script to re-execute itself indefinitely, spawning hundreds of python3 processes per second.

Before:

RUN() {
    case ... in *"Not enough arguments"*) exec $0 ;; esac
}
...
else
    exec $0
fi

Fix: Replace exec $0 with exit 0. If the script reaches a dead end, it should exit, not loop.

Bug 2: hint-hyprland.py — infinite retry on broken JSON

get_hyprctl_binds() had a while True loop that retried hyprctl binds -j forever when JSON parsing failed. On Hyprland 0.56.0, hyprctl binds -j returns malformed JSON (fields shifted, non-numeric values in numeric fields), causing the script to hang indefinitely in the retry loop.

$ hyprctl binds -j | python3 -m json.tool
# JSONDecodeError: Expecting value: line 15 column 16 (char 303)

Fix:

  • Try JSON first with a 5s timeout
  • If JSON is invalid, fall back to parsing the text output of hyprctl binds (no -j flag)
  • All subprocess calls have timeout=5 to prevent indefinite hangs

Impact

  • Fork rate dropped from ~568/s to ~7/s
  • System load returned to normal (was spiking to 100+ on a 14-thread CPU)
  • Keybinds hint (Super+/) now works on Hyprland 0.56.0 where hyprctl binds -j is broken

Testing

Tested on:

  • Hyprland 0.56.0 (commit 36b2e0c)
  • Kernel 7.1.4-1-cachyos
  • Python 3.11
# Before: hangs forever
$ python3 hint-hyprland.py --format rofi
# (no output, CPU spins)

# After: works correctly
$ python3 hint-hyprland.py --format rofi | head -3
 Window Management  ::: ::: Window Management
SUPER + Q > close focused window ::: exec ::: hyde-shell dontkillsteam
ALT + F4 > close focused window ::: exec ::: hyde-shell dontkillsteam

Summary by CodeRabbit

  • Bug Fixes
    • Improved keybinding detection by falling back to text-based parsing when structured output isn’t available.
    • Added a bounded command execution for keybind retrieval to avoid indefinite waiting.
    • Prevented the keybind dispatch script from repeatedly restarting when dispatch arguments are missing or selection can’t be performed.
    • Enhanced normalization of keybinding details (e.g., modifier/repeat/lock states, mouse/release options, and description handling) during fallback parsing.

keybinds_hint.sh: replace 'exec $0' with 'exit 0' to prevent infinite
self-re-execution when rofi produces no output or dispatch fails. This
was causing fork storms (~568 forks/s of python3) that led to system
load spikes.

hint-hyprland.py: replace infinite 'while True' retry loop with a
bounded approach. When 'hyprctl binds -j' returns invalid JSON (known
issue on Hyprland 0.56.0), fall back to parsing the text output of
'hyprctl binds' instead of sleeping and retrying forever. Added
timeout=5 to subprocess calls to prevent indefinite hangs.

Tested on Hyprland 0.56.0 + kernel 7.1.4 where 'hyprctl binds -j'
produces malformed JSON (fields shifted, non-numeric values in numeric
fields).
@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6bd7eb7-9476-4da5-a332-e94a9515108c

📥 Commits

Reviewing files that changed from the base of the PR and between fdf222a and c6e759c.

📒 Files selected for processing (1)
  • Configs/.local/lib/hyde/keybinds/hint-hyprland.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • Configs/.local/lib/hyde/keybinds/hint-hyprland.py

📝 Walkthrough

Walkthrough

The keybind helpers now use bounded hyprctl execution, parse non-JSON bind output as a fallback, normalize parsed fields, and terminate dispatch paths instead of restarting the script.

Changes

Hyprland keybind handling

Layer / File(s) Summary
Bounded bind retrieval and fallback parsing
Configs/.local/lib/hyde/keybinds/hint-hyprland.py
hyprctl binds -j uses a five-second timeout; failures fall back to normalized plain-text bind parsing with integer, boolean, and description fields.
Dispatch termination paths
Configs/.local/lib/hyde/keybinds_hint.sh
Insufficient arguments and non-single-line dispatch selection now exit successfully instead of re-executing the script.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant HintScript
  participant Hyprctl
  participant BindParser
  HintScript->>Hyprctl: Run binds -j with five-second timeout
  Hyprctl-->>HintScript: JSON output or command failure
  HintScript->>BindParser: Parse plain-text binds when JSON fails
  BindParser-->>HintScript: Return normalized bind dictionaries
Loading

Possibly related PRs

Poem

I’m a rabbit with binds in my hat,
No endless retries—imagine that!
JSON may flee, text takes its place,
Dispatch hops out with elegant grace.
exit 0 says, “The loop is done!”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main fix: stopping fork loops and JSON hangs in the keybinds hint flow.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Configs/.local/lib/hyde/keybinds/hint-hyprland.py`:
- Around line 45-67: Update the keycode parsing branch to accept signed numeric
values such as -1 instead of relying on value.isdigit(), preserving the parsed
integer for map_codeDisplay(). In the keybind parsing logic, replace the direct
value.lower() == "true" checks for repeat, locked, mouse, release,
non_consuming, and allow_input_capture with the existing parse_bool() helper so
numeric flags such as 1 remain valid.
- Around line 31-34: Update the bind-header detection in the parser so every
Hyprland bind variant, including flagged and combined forms such as bindl=,
bindm=, bindr=, bindl:m=, and bindr:Super=, starts a new record. Preserve the
existing current-record append and reset behavior in the surrounding parsing
logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9fdcfefa-65dc-4be5-940e-5f451330b517

📥 Commits

Reviewing files that changed from the base of the PR and between 1ca4d45 and fdf222a.

📒 Files selected for processing (2)
  • Configs/.local/lib/hyde/keybinds/hint-hyprland.py
  • Configs/.local/lib/hyde/keybinds_hint.sh

Comment thread Configs/.local/lib/hyde/keybinds/hint-hyprland.py Outdated
Comment thread Configs/.local/lib/hyde/keybinds/hint-hyprland.py Outdated
if current:
binds.append(current)
current = {}
elif ":" in line:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: this fallback is parsing a schema, rather than expressing distinct control flow. A field-to-parser mapping would make new Hyprland fields a one-line addition and, with explicit defaults, ensure partially parsed binds cannot later fail with missing keys in expand_meta_data.

BIND_DEFAULTS = {
    "modmask": 0,
    "submap": "",
    "key": "",
    "keycode": 0,
    "catch_all": False,
    "description": "",
    "has_description": False,
    "dispatcher": "",
    "arg": "",
    "repeat": False,
    "locked": False,
    "mouse": False,
    "release": False,
    "non_consuming": False,
    "allow_input_capture": False,
}

parse_bool = lambda value: value.lower() == "true"
parse_int = lambda value: int(value) if value.isdigit() else 0
FIELD_PARSERS = {
    "modmask": ("modmask", parse_int),
    "submap": ("submap", str),
    "key": ("key", str),
    "keycode": ("keycode", parse_int),
    "catchall": ("catch_all", parse_bool),
    "description": ("description", str),
    "dispatcher": ("dispatcher", str),
    "arg": ("arg", str),
    "repeat": ("repeat", parse_bool),
    "locked": ("locked", parse_bool),
    "mouse": ("mouse", parse_bool),
    "release": ("release", parse_bool),
    "non_consuming": ("non_consuming", parse_bool),
    "allow_input_capture": ("allow_input_capture", parse_bool),
}

# `startswith` also accommodates other Hyprland bind variants.
if line.startswith("bind"):
    if current:
        current["has_description"] = bool(current["description"])
        binds.append(current)
    current = BIND_DEFAULTS.copy()
elif ":" in line:
    key, _, value = line.partition(":")
    field = FIELD_PARSERS.get(key.strip())
    if field:
        destination, parser = field
        current[destination] = parser(value.strip())

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make sense, adjusted 😄

@kRHYME7

kRHYME7 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

#1824 (comment)

- Recognize all bind header variants (bindl=, bindm=, bindr=, etc.)
  not just 'bind' and 'bindd', using line.startswith('bind')
- Add parse_bool() helper to accept numeric flags (1/0) in addition
  to string 'true'/'false' for repeat, locked, mouse, release,
  non_consuming, allow_input_capture, and catchall fields
- Accept signed keycode values (e.g. -1) via try/except instead of
  value.isdigit() which rejected negative numbers
@kRHYME7

kRHYME7 commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Hi! I don't think adding a fix for a minor bug ( broken json) is needed. 0.56.1 fixes the json output already. Hyprland is fast changing, adding more guardrails for minor bug that was eventually fix doesn't make sense to me.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants