Skip to content

fix(windows): reduce idle agent detection CPU - #2651

Merged
ogulcancelik merged 2 commits into
masterfrom
issue/2642-windows-idle-detection
Aug 11, 2026
Merged

ogulcancelik merged 2 commits into
masterfrom
issue/2642-windows-idle-detection

Conversation

@ogulcancelik

@ogulcancelik ogulcancelik commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • skip Windows foreground-process discovery while a detected pane is stable, with immediate acquisition/restore/content wake-ups and a five-second safety observation
  • collect only PID, parent PID, and executable name in frequent Windows process snapshots
  • read command lines lazily and reuse prebuilt PID/parent indexes across pane detection
  • cache verified foreground-agent selections while invalidating on process death, PID reuse, identity changes, or topology changes
  • preserve Git Bash runtime-marker fallback without repeating its global command-line scan every 250 ms

Performance

Windows 11 VM, release build, CPU reported as percent of one logical core. Adding the scheduler gate on top of the process-discovery optimization produced:

Idle Pi panes Process optimization only Fused
1 1.042% 0.208%
15 2.708% 0.729%

The earlier process-discovery benchmark reduced 15 idle Codex panes from 7.917% to 1.979% and idle server I/O operations by roughly 93%. A separate Git Bash fallback control measured 1.875% median CPU before scheduler gating.

Validation

  • just check
  • native Windows scheduler, process-selection, cache, PID-reuse, Git Bash, and session-process tests
  • full-lifecycle Pi exit detected in 146 ms, forced process death in 24 ms, and relaunch returned to idle in 1.85 seconds
  • independent Windows benchmark by @Pimpmuckl confirmed the fused approach outperformed either optimization alone

Refs #2642

Thanks @Pimpmuckl for the scheduler approach, benchmark matrix, and Windows verification.

@kangal-bot kangal-bot added the ai-review Trigger automated AI reviews for pull requests admitted by the PR gate label Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

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: f8fad654-5427-495b-b325-5f71cb9b3dad

📥 Commits

Reviewing files that changed from the base of the PR and between ad901d6 and f2c62bc.

📒 Files selected for processing (2)
  • src/pane.rs
  • src/platform/windows.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/platform/windows.rs

📝 Walkthrough

Walkthrough

Windows process tracking now uses indexed ProcessSnapshot objects with lazy command metadata and descendant indexes. Foreground-agent selection uses validated caching. Windows foreground-group observation now runs conditionally based on lifecycle state, content changes, and safety intervals.

Changes

Windows process tracking

Layer / File(s) Summary
Indexed snapshots and lazy metadata
src/platform/windows.rs
Process enumeration builds indexed snapshots with parent-child relationships. Command metadata loads only when required. Ancestor, descendant, pane-shell, and session-process lookups use snapshot indexes.
Validated foreground-selection cache
src/platform/windows.rs
Foreground selections use process identities, creation times, liveness, signatures, topology, retention, and capacity checks. Cached foreground-job results retry with a fresh snapshot when required.
Agent detection and foreground observation
src/platform/windows.rs, src/pane.rs
Agent detection checks executable names and escaped or wrapped argv0 values. Windows reuses foreground observations unless lifecycle, content, or safety conditions require a new observation. Tests cover cache invalidation, PID reuse, topology changes, escaped agents, traversal cycles, and scheduling conditions.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PaneDetection
  participant ForegroundObservation
  participant ProcessSnapshot
  participant ForegroundSelectionCache
  PaneDetection->>PaneDetection: build shared process-probe input
  PaneDetection->>ForegroundObservation: observe when required
  ForegroundObservation->>ProcessSnapshot: enumerate and index processes
  ProcessSnapshot->>ForegroundSelectionCache: validate or create selection
  ForegroundSelectionCache-->>ForegroundObservation: return cached or fresh selection
  ForegroundObservation-->>PaneDetection: provide foreground process group
Loading

Possibly related issues

  • herdrdev/herdr issue 2642: Both changes modify Windows process and agent tracking in the paths associated with foreground observation scheduling.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: reducing CPU usage during idle Windows agent detection.
Description check ✅ Passed The description directly explains the Windows CPU optimizations, cache behavior, scheduler changes, and validation results.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue/2642-windows-idle-detection

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/platform/windows.rs (1)

1012-1017: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Run the process-handle syscalls before taking the cache lock.

remember executes under the global FOREGROUND_SELECTION_CACHE mutex. It calls ProcessIdentity::open for the shell, the selected process, and every descendant. remember_with_identities then calls entry.command(), which can trigger read_process_command (an OpenProcess plus remote memory reads). One global mutex therefore serializes those syscalls across all panes on the 250 ms detection cadence.

Collect the signatures and identities first, then take the lock only for the map mutation. remember_with_identities already accepts prepared identities, so the split is small.

As per coding guidelines: "Avoid unnecessary work in multiplicative paths such as rendering, layout, PTY parsing, detection, resizing, and client frame fanout; ... minimize terminal-core lock duration".

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5061130e-8979-4d41-bb32-918daa02e2f5

📥 Commits

Reviewing files that changed from the base of the PR and between ddffb6e and 61f4102.

📒 Files selected for processing (1)
  • src/platform/windows.rs

Comment thread src/platform/windows.rs Resolved
@ogulcancelik
ogulcancelik force-pushed the issue/2642-windows-idle-detection branch from 61f4102 to ad901d6 Compare August 11, 2026 02:41
@greptile-apps

ghost commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR reduces Windows idle agent-detection overhead by separating lightweight process snapshots from lazy command-line inspection and caching validated foreground selections.

  • Throttles Windows foreground-process observations while retaining content, lifecycle, restoration, and periodic recheck triggers.
  • Adds indexed process snapshots and lazy command metadata reads.
  • Caches foreground-agent selections with process-liveness, identity, topology, retention, and capacity checks.
  • Adds Windows-focused tests for observation scheduling, cache invalidation, PID reuse, Git Bash fallback, and process-tree traversal.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/pane.rs Adds Windows-only scheduling for foreground observations while preserving immediate and periodic lifecycle checks.
src/platform/windows.rs Introduces lightweight indexed snapshots, lazy command inspection, and validated foreground-selection caching for Windows process detection.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Tick[Pane detection tick] --> Gate{Foreground observation due?}
  Gate -->|No| Previous[Reuse last foreground process group]
  Gate -->|Yes| Snapshot[Obtain lightweight Windows process snapshot]
  Snapshot --> Cache{Validated selection cached?}
  Cache -->|Yes| Job[Return cached foreground job]
  Cache -->|No| Select[Traverse indexed process topology]
  Select --> Lazy[Read command metadata lazily as needed]
  Lazy --> Validate[Open identities and validate creation times]
  Validate --> Remember[Cache eligible foreground selection]
  Remember --> Job
  Previous --> Probe{Process probe required?}
  Job --> Probe
  Probe -->|Yes| Agent[Update detected agent state]
  Probe -->|No| Sleep[Wait for next tick]
Loading

Reviews (2): Last reviewed commit: "fix(windows): gate agent process discove..." | Re-trigger Greptile

@JJLiebig

ghost commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Also went performance diving with a bit of profiling and some help from 5.6 pro after filing the issue, going to test this branch head to head, will report back.

Edit:

I ran both current heads against the same baseline on the same machine.

The fixture used real Pi 0.84.1 sessions in offline mode, with every pane detected as Idle. Each result is the median of seven 15-second samples after a 20-second warm-up. I also removed the Git sidebar tokens so the separate Git polling issue did not affect the result.

Idle Pi panes Baseline master scheduler-gates-approach #2651
1 10.32% 0.92% 5.95%
15 12.02% 6.49% 5.75%

The other approach I cooked up with 5.6 Pro uses scheduler gates in the pane runtime. It avoids running Windows foreground process discovery on stable idle ticks, while preserving immediate checks for acquisition and restore paths plus the periodic lifecycle safety check.

That is why it does especially well with one idle pane. The tradeoff is that it does not make process discovery itself cheaper, so the remaining safety checks still scale with the number of panes.

Your branch tackles the other side. It keeps the existing observation schedule but makes each observation cheaper through lightweight snapshots, lazy command-line reads, indexed process trees and cached foreground selections. That scales better at 15 panes and keeps the optimization inside the Windows platform layer. The tradeoff is that scheduled observations still happen, and the cache needs identity and invalidation handling.

Both approaches reduced Windows process I/O from roughly 1,580 ops/s to around 120 ops/s with 15 panes.

So this does not look like a clean either/or. The scheduler gates win the common one-pane idle case, while your snapshot and selection changes scale better across many panes. They touch different layers and look potentially stackable. I linked the branch so you can pick whichever parts make sense for the final PR.

I can also mix and match this a bit and iterate on a combined approach, if it's too annoying to test with a VM on your side.

Edit2:

Curiosity got the better of me and since both integrated easily, I tested a fused approach, updated table below.

Pretty cool results ngl.

Idle Pi panes Baseline master scheduler-gates-approach #2651 Fused
1 10.32% 0.92% 5.95% 0.41%
15 12.02% 6.49% 5.75% 3.18%

@ogulcancelik
ogulcancelik force-pushed the issue/2642-windows-idle-detection branch from ad901d6 to f2c62bc Compare August 11, 2026 14:07
@ogulcancelik

ghost commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

@Pimpmuckl I integrated your scheduler-gate commit and kept your authorship. I also reproduced the fused result on the Windows VM: 0.208% median with one idle Pi pane and 0.729% with 15, versus 1.042% and 2.708% for the process optimization alone. Full-lifecycle exit, forced-death detection, and relaunch transitions still passed. Thank you for profiling this and putting together the complementary approach.

@ogulcancelik

ghost commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

@Pimpmuckl could you test this version too? it looks much better

@JJLiebig

ghost commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

@Pimpmuckl could you test this version too? it looks much better

Tested the current PR head:

Same fixture as before: Pi 0.84.1 offline, every pane detected as Idle, non-Git cwd, Git sidebar tokens removed, 20-second warm-up, then seven 15-second samples.

Idle Pi panes Earlier fused Current head
1 0.41% 0.52%
15 3.18% 2.71%

The current ranges were 0.31-0.94% for one pane and 1.98-3.02% for 15 panes. Process I/O stayed flat at roughly 21 ops/s and 120 ops/s.

This is firmly in range of fluctuation, I don't run fixed CPU frequency so a couple percent up/down are expected, looks good to me.

@ogulcancelik
ogulcancelik merged commit 06ca0ba into master Aug 11, 2026
@ogulcancelik

ghost commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

ty!!

@kangal-bot kangal-bot removed the ai-review Trigger automated AI reviews for pull requests admitted by the PR gate label Aug 11, 2026
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