Skip to content

fix: reduce repeated Git work during repository requests - #146273

Merged
steipete merged 5 commits into
mainfrom
codex/git-worktree-worker-refactor
Sep 12, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/git-worktree-worker-refactor

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes #146252

What Problem This Solves

Repository-heavy Gateway requests repeat Git subprocesses and large path/output processing. Concurrent branch-picker, diff, and PR-sidebar reads duplicate work, while managed-worktree snapshots rebuild inventories that compete with interactive requests.

Why This Change Was Made

Reuse the existing worker pool for complete Git read and worktree inventory operations, with a dedicated metadata worker, up to two content workers, and one maintenance worker. These workers are created lazily and retire when idle. The Gateway remains the owner of subprocesses, mutation authority, registry writes, and cleanup; workers receive owned byte buffers and perform decoding, parsing, and inventory work. Batched host exchanges preserve parallel reads without competing for the pool's serial request channel.

One lifecycle-owned read cache shares in-flight branch, diff, and baseline requests. PR context and branch facts retain their established 75-second freshness. Explicit refresh replaces the generation, each subscriber receives an independent result, and cancellation only stops shared work after its last caller leaves. The final canceled caller waits for worker and subprocess teardown. Working-tree results are not retained across completed requests.

Snapshots reuse operation-local inventories and verify their pinned checkout HEAD atomically when publishing the recovery ref. Preparatory cancellation joins Git children and temporary-index cleanup. Once destructive deletion starts, it settles before cancellation returns, preserving the complete recovery snapshot. The existing allocation lease continues to protect cross-process create/remove/restore operations. Creation and restore retain the filesystem checkout owner, including Btrfs acceleration; all of its Git commands carry the same cancellation, current-authority checks, and process supervision, including queued fallback branch cleanup.

Storage keeps the existing managed-worktree rows, provisioned-file chunks, and snapshot ref format. This PR adds no schema, migration, or persistent cache. Filesystem-acceleration template storage is already part of main.

User Impact

Branch discovery normally needs two Git starts instead of six, and concurrent identical reads share that work. Large repository scans and diff parsing run off the Gateway event loop while preserving branch selection, diff results, provisioned-file rules, and worktree restoration.

Evidence

Exact-head CI passed for 5e22ac404ba66944dd927e99f57042e39334b531.

  • A full local build produced the packaged Git worker entry. Changed-file gates, architecture checks, and independent review through P2 passed.
  • Focused coverage includes 108 worker/cache/Git tests (two existing platform-specific cases skipped), 53 integration tests, 42 checkout/diagnostics/lifecycle tests, and 79 final diff/capacity/acceleration tests. These suites overlap and are not a combined unique-test count.
  • Real-Git regressions were proved failing before and passing after fixes for child cancellation, final-subscriber teardown, queued HEAD/authority changes, destructive-deletion cancellation, and metadata starvation behind two held diffs.
  • CI-discovered type cycles, export collisions, and observers of retired execution paths were repaired. The unrelated QA selector failure was fixed upstream by fix(qa): select the renamed diagnostics browser test #146323 and its 20 scenario tests passed after the patch-identical rebase.

Paired live Gateway comparison

Linux Testbox run: baseline 35b237db14bf619c2b58b1ac4afa9a3832b8f090 versus the exact PR head, candidate tree b9a9df7854db15915efa7ec5e39e538f9d1eb9a5. Both pinned sources passed the maintained sourcePerformance build profile on the same 4-vCPU AMD EPYC Linux host, Node 24.19.0, Git 2.52.0. Three runs per version used B/C/C/B/B/C order and synthetic repositories with 6,000 and 80 generated files.

All six runs passed: 143 complete normalized RPC responses per run, 858 responses total, identical across versions. Only generated identities, fixture paths, and timestamps were normalized. Branch/diff freshness after external edits, all/uncommitted/commit diff scopes, main and secondary sessions, staged/unstaged/binary/provisioned content, archive/unarchive, manual remove/restore, unpushed HEAD, registry binding, and cleanup were checked. All Gateways exited cleanly; 1,207 readiness probes had zero failures.

Measurement Baseline Candidate
20 concurrent branch reads: median RPC 197.42 ms 5.82 ms
Git starts for that branch burst 120 2
20 concurrent diff reads: median RPC 491.02 ms 63.93 ms
Git starts for that diff burst 240 12
Branch median while two independent diffs are pending 95.99 ms 9.31 ms
Overall readiness p95 24.34 ms 7.66 ms
First branch RPC 15.14 ms 94.05 ms
First all-scope diff RPC 64.52 ms 169.69 ms
Median of each run's maximum sampled RSS 520.27 MiB 705.58 MiB
Median Gateway-process CPU over measured phases 1.70 s 1.94 s

All 30 candidate branch requests in the mixed test finished while both diffs were still pending. This verifies metadata isolation through real RPCs. The second content worker was cold: total mixed-phase wall time increased from 109.02 to 123.01 ms even though branch latency improved substantially.

The tradeoff is explicit: lazy worker startup adds cold-call latency and resident memory; moving work off the event loop does not guarantee lower total CPU or faster individual operations. Sequential diff phase time rose from 292.13 to 309.44 ms, session archive from 206.80 to 235.26 ms, and manual removal from 196.16 to 248.84 ms. The worst individual readiness probe rose from 91.03 to 119.45 ms. The measured concurrency benefit justifies these costs for this change; workers remain bounded and retire after 30 seconds idle. RSS was sampled at phase boundaries, not continuously. CPU includes Gateway worker threads and excludes Git child CPU, with 10 ms counter resolution. These are synthetic-host results, not a production latency claim.

The initial pinned-baseline full build timed out after 120 seconds rendering source config --help, after runtime, SDK, and UI compilation passed. Its logs were preserved; the successful paired run used sourcePerformance symmetrically without product changes. Evidence archive SHA-256: 5c41f4401f8804626b23e5e5c00ec65d4910f16aef3e7d06fb5737fae88b0a28.

The automated storage warning refers to extracted size-estimation and repository-path code, not a persistence change. Existing restore contracts are exercised above; there is no new stored format to migrate. The shared cross-process allocation lease remains intentional. The Team server was not redeployed or modified.

@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 3:42 PM ET / 19:42 UTC (Revision 5).

ClawSweeper review

What this changes

Shares concurrent repository reads and moves Git output processing and worktree snapshot inventories onto bounded background workers while preserving Gateway-owned execution and cleanup.

Merge readiness

⛔ Blocked before merge - 3 items remain

This remains useful work for the linked performance issue. The dedicated metadata worker addresses the previous contention concern, and no blocking correctness defect was found. Comparative performance evidence remains outstanding.

Priority: P2
Reviewed head: 5e22ac404ba66944dd927e99f57042e39334b531

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation is coherent and has meaningful boundary coverage, with comparative performance validation still required.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied MEMBER association exempts this PR from the ordinary external-contributor proof gate. Inspected real-Git regressions cover worker teardown and revoked publication; the separately required paired Gateway performance measurements remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied MEMBER association exempts this PR from the ordinary external-contributor proof gate. Inspected real-Git regressions cover worker teardown and revoked publication; the separately required paired Gateway performance measurements remain pending.
Evidence reviewed 8 items Current main still performs branch discovery directly: Fetched main retains direct branch inventory and symbolic-ref queries in the service. The new Git worker and read-cache files are absent from both fetched main and the supplied latest release tag.
Metadata capacity is now separate: Branch and checkout-context operations use one dedicated worker; content operations use one or two workers, and maintenance uses another. This addresses the prior review's specific concern about diffs occupying metadata capacity.
Read-cache ownership: Inspected complete cache modules: dirty checkout results are shared only while pending, sidebar facts retain 75-second freshness, refresh replaces the generation, subscribers receive independent results, and final cancellation joins underlying teardown.
Findings None None.
Security None None.

How this fits together

Repository requests feed branch pickers, session diffs, and PR status in the Control UI. Managed worktrees use the same Git execution infrastructure to prepare recoverable snapshots before removing checkouts.

flowchart TD
  A[Repository requests] --> B[Shared read cache]
  B --> C[Metadata and content workers]
  D[Worktree lifecycle] --> E[Maintenance worker]
  C --> F[Gateway Git execution]
  E --> F
  F --> G[Repository results]
  E --> H[Guarded snapshot publication]
Loading

Before merge

  • Resolve merge risk (P1) - The new worker lanes introduce additional resident memory and queueing tradeoffs; their effect on Gateway latency and RSS under concurrent repository requests remains unmeasured in the captured evidence.
  • Complete next step (P2) - Record the promised paired Gateway measurements, including before/after seconds and RSS, Git process counts, and normalized RPC equivalence for the current integrated implementation.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +1359, Tests +1178, Docs +4, Other 0. Total +2541 across 61 files.

View PR surface stats
Area Files Added Removed Net
Source 37 3410 2051 +1359
Tests 22 1526 348 +1178
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 61 4941 2400 +2541

Review metrics

Metric Value Why it matters
Worker capacity 1 metadata, 1–2 content, 1 maintenance; 30-second idle retirement Metadata isolation resolves the previous queue contention concern while adding a measurable memory tradeoff.
Production versus test growth Production net +1,359 lines; tests/support net +1,178 lines The stated justification is shared read ownership and supervised worker execution; comparative measurements must establish the resulting performance benefit.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/worktrees/capacity.runtime.ts, migration/backfill/repair: src/agents/worktrees/capacity.ts, migration/backfill/repair: src/agents/worktrees/repository-paths.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #146252
Summary: This PR is the explicit implementation candidate for the open repository-inspection performance issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Complete the paired Gateway comparison (recommended)
    Record timing, RSS, Git process counts, and normalized response equivalence for the integrated implementation before accepting its worker-capacity tradeoff.

Technical review

Best possible solution:

Retain the single host execution owner and dedicated metadata capacity, with paired Gateway results demonstrating lower repeated work without unacceptable latency or memory regressions.

Do we have a high-confidence way to reproduce the issue?

Yes, for repeated work: current main independently performs Git discovery for concurrent branch requests, and the linked issue reports six Git starts per request. This review did not execute the Gateway or measure contention.

Is this the best way to solve the issue?

Yes, structurally: extending the existing worker pool and consolidating read ownership preserves established contracts; the remaining question is whether measured latency and memory justify the implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2f97cdbacace.

Labels

Label justifications:

  • P2: This improves repository-heavy Gateway responsiveness without evidence of an emergency or broadly unusable workflow.
  • merge-risk: 🚨 availability: Additional worker isolates and bounded queues can affect request latency and memory pressure beyond what functional CI establishes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied MEMBER association exempts this PR from the ordinary external-contributor proof gate. Inspected real-Git regressions cover worker teardown and revoked publication; the separately required paired Gateway performance measurements remain pending.

Evidence

What I checked:

  • Current main still performs branch discovery directly: Fetched main retains direct branch inventory and symbolic-ref queries in the service. The new Git worker and read-cache files are absent from both fetched main and the supplied latest release tag. (src/agents/worktrees/service.ts:1246, 2f97cdbacace)
  • Metadata capacity is now separate: Branch and checkout-context operations use one dedicated worker; content operations use one or two workers, and maintenance uses another. This addresses the prior review's specific concern about diffs occupying metadata capacity. (src/infra/git-worker.ts:60, 5e22ac404ba6)
  • Read-cache ownership: Inspected complete cache modules: dirty checkout results are shared only while pending, sidebar facts retain 75-second freshness, refresh replaces the generation, subscribers receive independent results, and final cancellation joins underlying teardown. (src/infra/git-read-cache.ts:23, 5e22ac404ba6)
  • Snapshot publication and cancellation safeguards: Snapshot publication verifies the pinned HEAD inside an update-ref transaction. Inspected lifecycle regressions exercise real Git fetch cancellation, temporary-directory cleanup, and queued publication rejection after authority revocation or HEAD movement; these tests were read, not executed during this review. (src/agents/worktrees/snapshot-inventory.ts:319, 5e22ac404ba6)
  • Performance evidence remains required: The scoped agent policy requires before/after seconds and RSS for performance changes. The complete supplied PR body explicitly says paired Linux Gateway measurements and the normalized RPC comparison remain in progress; the previous completed review requested the same evidence. (src/agents/AGENTS.md:61, 5e22ac404ba6)
  • Captured discussion and canonical issue: The supplied snapshot, sourceRevision ecc952416e793207804471d5527d65bb75c769349ea7cef2580aa35aae4e5644, pairs this maintainer-labeled PR with the open issue Gateway Git inspection repeats work and competes with interactive requests #146252. That issue requests shared Git inspection, bounded workers, preserved recovery, and paired Gateway measurements. The merged QA selector repair fix(qa): select the renamed diagnostics browser test #146323 is separate base-branch work.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Doksanbir: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add the promised paired Gateway timing, RSS, Git process counts, and normalized repository-response comparison for the current integrated implementation.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-12T18:02:58.606Z sha 0dfa63376088ccc6183e4ac21baaf6abb3d49513 :: blocked before merge. :: none
  • reviewed 2026-09-12T18:16:36.401Z sha 76ec9ec3cc8e702d5a756478063f7be7a8dbfeec :: blocked before merge. :: none
  • reviewed 2026-09-12T18:34:11.425Z sha 8686579a06f9d9774ec63963b71380eb87d5b3e2 :: blocked before merge. :: none
  • reviewed 2026-09-12T19:00:44.745Z sha 37ef75a5178a6c3e0ff87a3b7bad5768ef6d032f :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/git-worktree-worker-refactor branch from 0dfa633 to 76ec9ec Compare September 12, 2026 18:08
@steipete
steipete marked this pull request as ready for review September 12, 2026 18:09
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Sep 12, 2026
@steipete
steipete force-pushed the codex/git-worktree-worker-refactor branch from 8686579 to 37ef75a Compare September 12, 2026 18:53
Run repository reads and snapshot inventories on reusable workers while the
Gateway retains subprocesses, authority, registry writes, and cleanup. Share
concurrent reads and preserve sidebar freshness without caching dirty state
across completed requests. Verify snapshot HEAD atomically at publication and
join cancellation through worker and subprocess teardown.

Refs #146252
@steipete
steipete force-pushed the codex/git-worktree-worker-refactor branch from 37ef75a to 5e22ac4 Compare September 12, 2026 19:35
@steipete
steipete merged commit f0fafba into main Sep 12, 2026
193 of 194 checks passed
@steipete
steipete deleted the codex/git-worktree-worker-refactor branch September 12, 2026 20:03
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
…6273)

* fix: reduce repeated Git work during repository requests

Run repository reads and snapshot inventories on reusable workers while the
Gateway retains subprocesses, authority, registry writes, and cleanup. Share
concurrent reads and preserve sidebar freshness without caching dirty state
across completed requests. Verify snapshot HEAD atomically at publication and
join cancellation through worker and subprocess teardown.

Refs openclaw#146252

* test: track Git history fixture cleanup

* refactor: share Git execution types without a worker cycle

* fix: retain Git authority through accelerated checkout cleanup

* fix: reserve Git metadata capacity and finish worker cutover
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gateway Git inspection repeats work and competes with interactive requests

1 participant