Skip to content

fix(worktrees): keep pack maintenance running during cleanup - #197287

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-base-consolidation-starved-by-load-20260919
Nov 11, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-base-consolidation-starved-by-load-20260919

Conversation

@steipete

@steipete steipete commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Git pack maintenance stalling for hours when checkout cleanup waits on storage pressure or a large deletion backlog.

User Impact

Managed repositories can consolidate a burst of small packs while the Gateway is busy. Checkout cleanup keeps its storage-pressure protection; foreground preparations retain short, nonwaiting checkout leases.

Why This Change Was Made

Git maintenance was behind the entire cleanup sweep, which can pause indefinitely on I/O pressure. An independent five-minute wake now calls the same maintenance owner. Its hourly deadline still governs routine tasks; between hourly passes, at least 512 eligible small packs in one promisor class trigger bounded consolidation. Thresholds derive from existing pack budgets. Unfinished 250-ms retirement slices resume at the next wake even below that threshold, without repeating hourly graph work. No config, schema, or cache was added. Lease deferrals log the reason, and successful pack reductions log counts.

Evidence

The first CI head exposed two thaw-timer fixture failures: an unrelated real Git inventory interfered with recovery assertions, and a fake-clock wake waited for suspended admission that the test would only reopen after that wake completed. The repair isolates worktree maintenance in the thaw-specific fixture and stubs Git inventory in the shared timer fixture. All 69 Gateway timer/worktree scheduler tests now pass. The nine shared-fixture consumer files also pass all 127 tests after adding the method to their worker-free telemetry service stub. Production behavior and the measured code are unchanged.

Acceptance rule, recorded before measurement: keep cleanup blocked under simulated I/O pressure; restore the same synthetic 1,033 pinned baseline packs plus 600 new 64-KiB promisor packs before each sample. Use actual Gateway scheduling, registry, maintenance leases and native Git. Candidate must recover near baseline within a virtual hour and preserve the exact object set; parent must reproduce lack of progress. Five interleaved pairs plus five A/A pairs; report owner wall time, JS/native CPU and allocation as the cost of newly admitted work, not a speedup over doing no maintenance. Fixture has 62,000 files totaling 1.116 GB and 3,000 registry rows. APFS local proof does not establish btrfs performance, a 35-GiB agent DB workload, or post-deployment production convergence.

Scheduler and native 600-pack regressions fail on exact parent 3a6cc6597d1d1d32a4bef83fd3041fedf5f48e76; 88 focused tests pass with one existing Linux-only skip. The extended retirement-continuation regression also passes. Native burst test: 14.9 seconds; full focused invocation: 141 seconds including compilation. Codex autoreview of the complete local change is scoped-clean through P2. pnpm check:changed --staged completed; its three local lint findings were repaired and targeted core/script lint and script typechecking pass. The final fixture repair also completed pnpm check:changed --staged: all checks passed except the same 89 ordered dead-export findings. The only remaining failure is the unrelated dead-export scan: the exact parent also fails, with source-causal attribution recorded for all 57 production and 32 full-tree entries. These remain main regressions, not ignored noise; the introducing commits are listed below.

Production growth is 80 lines, required to separate admission, derive backlog policy, preserve unfinished retirement state in the existing deadline record, and record lease/count outcomes. No second maintenance owner or pack inventory cache. The scoped 93-line test allocation covers the two missing regression boundaries and extends the existing retirement contract; the shared scalar is unchanged. Changed modules have no Control UI imports. No live service operations or deployment are part of this PR.

Five counterbalanced A/B pairs and five A/A control pairs passed on the measured production head 8683fa86c7fe971c72fc9a9f9a976d00037bc58c against exact parent 3a6cc6597d1d1d32a4bef83fd3041fedf5f48e76. All 64,254 objects remain present; a subsequent quiescent tick performs zero consolidations. The baseline reaches a virtual hour without admitting any Git work. Candidate reaches near-baseline in 5–15 virtual minutes (median 10), using one to three bounded passes.

Metric (median / p95; five samples) Parent, starved Candidate, completed work
Packs after burst 1,633 / 1,633 1,035 / 1,036
Measured owner wall 0.718 / 0.800 ms 9.049 / 12.076 s
Native Git CPU 0 / 0 7.570 / 10.270 s
Node process CPU 4.955 / 7.999 ms 644.146 / 926.991 ms
Main-thread CPU 2.334 / 2.360 ms 222.987 / 294.301 ms
Exact V8 allocation 3.978 / 4.901 MiB 79.959 / 93.390 MiB
Native peak RSS no Git process 74.062 / 75.609 MiB

This restores bounded background work and therefore spends CPU/allocation that the broken scheduler never spent. It is not a claim that compaction itself became faster. Candidate wall spread is 7.209–12.076 seconds, reflecting one to three retirement slices. A/A wall medians are 0.845 / 0.840 ms (0.7% drift); every control retains 1,633 packs. Recorded one-minute host load spans 10.6–16.8. A quiet candidate probe takes 60.35 ms wall, 13.71 ms main CPU, and 8.60 MiB allocation median for 3,000 registry rows, with two Git metadata commands and no consolidation.

Rerunnable workload: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/worktree-pack-backlog-measure.ts --output <owned-fixture> --prepare, then the same command without --prepare and with a unique --report <sample>.json. Set OPENCLAW_BENCH_BASELINE_DIR to the qualified exact-parent checkout for A; unset it for B. Fixture creation, restoration, warmup, and object verification are outside measured ticks. A failed sparse-overlay setup was excluded; the qualified full parent checkout supplied all successful baseline samples. Production convergence after deployment remains unverified; no live runs or deployment were performed.

Inherited dead-export gate regressions: exact-parent reproduction and introducing commits

The canonical failed checker exits 1 on the clean exact parent after 279.82 seconds. Both ordered finding lists match the candidate exactly: 57 production / 32 full-tree, scripts 0, with no dependency-resolution errors. These are main regressions requiring separate repairs. No ignore list or shared budget was raised to mask them.

Findings Production / full-tree Introducing commit / PR and causal evidence
Knowledge tool-result-contract.ts: Incomplete, Issue, LeanDefinition, LeanRecordFields, page, Via; tool-results.ts: AGENT_HIT_LIMIT, AGENT_RECORD_MAX_CHARS, and 14 lean* exports; tool-rows.ts: rowDate 23 / 21 9b7dcdc7a66dc1bbcb0767b8109e798eb826954e, #196767, creates all three files and these exports. Their production consumers are local to each declaring module; AGENT_HIT_LIMIT and leanRecord have external test consumers. Public tool registration imports leanToolResults, which uses its local projection helpers. No subsequent owner change before the exact parent explains these findings.
Telegram TelegramWidgetMessage, formatTelegramWidgetRequestText 2 / 1 b22f35f7ed76552778bc185cc65a6177e8ad8b02, #196991, creates both files and exports. The message type and formatting function are used inside their declaring owners; only the formatting function has an external test consumer.
OpenClaw ID BoundKeys, nextBindingSeq, TunnelStagedMessage 3 / 3 5f2f21a7ee193fdd4aa8ac42a407eefc04905255, #196388, creates rebind-operations.ts with the two exports and adds the exported IPC type. All direct uses remain within the declaring modules.
planOpenClawModelsJsonSource, filterToolsByClientCaps; auth-storage AuthCredential, AuthStatus, AuthStorageBackend; model-registry ResolvedRequestAuth; linux-oom-score resolveOomScoreWrappedCommand, spawnWithInheritedOomScore 8 / 2 625945b7ae01d5eea91aba5285da1a327b2a5f9f, #192552, migrates production consumers to core/leaf owners while retaining facade exports. The source-causal audit was reused after verifying unchanged owners.
nestRequiredSummaryHeadings 1 / 1 c7152f3bda8e52c24fc2fda83911e7e1c24fb0f2, #196207, moves the former external production consumer into the quality owner but leaves the export.
MAX_MCP_TOOL_DIRECTORY_BYTES, sanitizeMcpToolDirectoryDescription 2 / 0 80ba593b8b14bb3f5ddd6634a92805e04707b25c, #196252, introduces exports with local production use and external test consumers.
projectLeaseDiagnosticFrames 1 / 0 2c4e34a72f490c710bc155319fcabf872f482b3e adds the projection helper, used internally in production and externally by tests.
createKeyFile 1 / 0 37a3b162a0c58aaceb1634aaef726d0e178a529c, #196380, introduces an exported helper whose production calls remain within tunnel-child/keyfile.ts. Other old key helper findings now have consumers and are absent; they are not counted here.
replyWithBillingRouteWarnings 1 / 0 56617cd00086481212d29745ed71f5feb8a40b9e, #191326, introduces helper with same-owner production use and external test-only use.
Ten provider-runtime.ts exports and provider-external-auth.ts: resolveExternalAuthProfilesWithPlugins 11 / 0 f63e5cd0f6d38f1d0438978255d9e244183864c3, #190205, narrows the broad deferred provider-runtime namespace import to actual auth/catalog owner loaders, exposing stale facade exports. A source counterfactual restored only the old namespace loader and removed exactly these eleven findings, leaving other findings unchanged. Current owner blobs are identical; that historical cutover proof is reused, not repeated.
Provider type facades ProviderAuthOptionBag, ProviderNonInteractiveApiKeyCredentialParams, ProviderNonInteractiveApiKeyResult, ProviderResolveNonInteractiveApiKeyParams 4 / 4 cf1ae7bb6a729a7f13a28ca2ef9d6f108c00566f, #190544, moves consumers to the provider-auth-types owner while retaining broad barrel exports.
Total 57 / 32 Source-causal groups account for every candidate signature.

@clawsweeper

clawsweeper Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 11, 2026
@steipete
steipete marked this pull request as ready for review November 11, 2026 16:29
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T17:00:07.754523Z 69bfbf6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Ready at 8683fa86c7fe971c72fc9a9f9a976d00037bc58c. Please review the independent Git-maintenance wake, derived small-pack threshold, and retirement continuation while checkout cleanup is held under I/O pressure. The PR now includes native synthetic burst measurements, regression proof, and exact-parent attribution for the remaining unrelated dead-export gate failure.

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR schedules independent Git maintenance checks and resumes unfinished pack retirement between hourly passes.

Example: Checkout cleanup remains blocked under storage pressure after 600 small promisor packs arrive.

  • Before: The supplied baseline measurements retain 1,633 packs without admitting Git maintenance.
  • After: The supplied candidate measurements reach 1,035–1,036 packs within 5–15 virtual minutes while preserving all 64,254 objects.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused repair has no remaining findings and meaningful native-Git owner-level evidence; proof confidence remains scoped to the in-process measurements.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied APFS comparisons exercise the actual scheduler, registry, maintenance leases, and native Git under simulated cleanup pressure, and the follow-up changes only test fixtures and their allocation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Managed repositories accumulate small packs while checkout cleanup waits on storage pressure or paced removals.
Reason: The maintainer-authored direction restores maintenance progress while retaining cleanup pressure protection, existing resource budgets, and foreground checkout admission.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current maintenance starvation path, and the previous fixture finding is resolved. No remaining actionable defect was found; exact-head CI is still pending.

Priority: P2
Reviewed head: 69bfbf678040e673eaea61fa7073a46b3bfc5e7f

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied measurements exercise production owners in one process, without a started Gateway or deployed btrfs workload.
Agent review details

How this fits together

The Gateway scheduler invokes the managed-worktree service, whose maintenance owner inventories registered repositories and uses leases and native Git to consolidate packs without changing their object set.

flowchart TD
  A[Gateway scheduler] --> B[Checkout cleanup]
  A --> C[Independent Git wake]
  B --> D[Existing maintenance owner]
  C --> D
  D --> E[Repository maintenance lease]
  E --> F[Native Git consolidation]
  F --> G[Bounded pack retirement]
Loading

Technical review

Best possible solution:

Keep the independent wake and backlog continuation in the existing lease-protected maintenance owner while retaining hourly routine work.

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

Current-main source places Git maintenance after potentially paused cleanup, and the supplied exact-parent comparison reports no admitted Git work while cleanup remains blocked; this review executed no target code.

Is this the best way to solve the issue?

The patch repairs scheduling at the existing owner, preserves bounded consolidation and foreground lease behavior, and adds only the deadline-record continuation needed to finish interrupted retirement.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1d72ad079047.

Provenance checked

  • Hourly maintenance deadline changes intended behavior with a stated reason (75e5ea6: Prevent frequent archives from repeatedly launching housekeeping, with large pack backlogs converging over hourly passes.)
  • Checkout lease separation and retirement budget keeps the original intent (280e1de: Keep foreground preparation from waiting behind pack rewriting and leave valid duplicate inputs when short retirement slices expire.)
  • Cleanup pressure pacing keeps the original intent (aedae9d: Avoid sustained checkout deletion bursts that overwhelm shared storage.)
  • Verified bounded consolidation keeps the original intent (99aed8a: Consolidate verified, bounded pack batches without repository-wide MIDX rebuilding or loss of unique objects.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 280e1de adds src/agents/worktrees/git-maintenance.ts:418 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 280e1de139e7; files: src/agents/worktrees/git-maintenance.ts)
  • RoboClaw: Raw commit 0d4c4fb adds src/agents/worktrees/git-maintenance.ts:403 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0d4c4fb0fc5c; files: src/agents/worktrees/git-maintenance.ts)

PR surface

Source +81, Tests +92, Docs 0, Other +418. Total +591 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 113 32 +81
Tests 5 95 3 +92
Docs 1 4 4 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 418 0 +418
Total 12 630 39 +591

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus regression growth Production net +80 lines; tests and shared fixtures net +93 lines Growth supplies independent scheduling, derived backlog admission, retirement continuation, and distinct scheduler/native-Git regressions using existing owners.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Restores bounded background pack convergence when prolonged cleanup waits prevent maintenance from running.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-11T16:36:37.970Z sha 8683fa8 :: needs changes before merge. :: [P2] Isolate the new Git wake in the thaw timer fixtures

Reviewed November 11, 2026, 12:04 PM ET / 17:04 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

Addressed item 1, “Isolate the new Git wake in the thaw timer fixtures.”

  1. The thaw-only fixture now isolates the unrelated worktree scheduler at src/gateway/server-maintenance.test.ts:90–96, so its synchronous fake-clock assertions no longer join a suspended admission waiter. The shared timer fixture stubs Git inventory at src/gateway/test-helpers.maintenance-state.ts:27, and the worker-free telemetry service stub declares the method at src/gateway/server-maintenance.telemetry.test.ts:45. Production admission and shutdown behavior are unchanged. The dedicated independent-wake regression and native pack/lease tests remain intact.

Both original CI failures reproduced locally before the repair. All 69 tests in the Gateway timer/worktree scheduler files now pass, and all 127 tests across the nine shared-fixture consumer files pass. The initial consumer run exposed the missing telemetry stub method; its nine failures were repaired and rerun. Codex autoreview of the final fixture repair is scoped-clean through P2. Full check details and the exact-parent dead-export attribution remain in the PR body.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 11, 2026
@steipete
steipete merged commit b984dfb into main Nov 11, 2026
137 of 139 checks passed
@steipete
steipete deleted the steipete/perf-micro-base-consolidation-starved-by-load-20260919 branch November 11, 2026 17:14
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
…w#197287)

* fix(worktrees): keep pack maintenance running during cleanup

* test(gateway): isolate worktree maintenance in timer fixtures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant