Skip to content

perf(doctor): parallel I/O for repair sequence and plugin dep cleanup - #85497

Closed
samson1357924 wants to merge 11 commits into
openclaw:mainfrom
samson1357924:fix/85333-optimize-doctor
Closed

samson1357924 wants to merge 11 commits into
openclaw:mainfrom
samson1357924:fix/85333-optimize-doctor

Conversation

@samson1357924

@samson1357924 samson1357924 commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Performance optimization for doctor --fix (Phase 1A)

Issue: #85333

Changes

  1. repair-sequencing.ts: Parallelized 3 I/O-only repair steps (plugin dep cleanup, legacy OAuth sidecar repair, stale OAuth shadow repair) using Promise.all with safety contract documentation.

  2. plugin-dependency-cleanup.ts: Parallelized per-plugin directory walks in collectLegacyExtensionDebris (50+ plugins scanned concurrently) and root-level scans (3 roots × 2 sub-paths = 6 concurrent reads).

  3. Test fixes: Removed fragile ordering assertion (Promise.all implementation detail), added explicit assertions for all 3 parallel branches.

Behavior or issue addressed

openclaw doctor --fix performance regression from 5.19 (~55s) to 5.20 (~229s) on VPS. Phase 1A optimizes the repair sequence and plugin dep cleanup to run independent I/O operations concurrently instead of serially.

Real environment tested

  • Machine: Mac mini (M2, 24GB RAM, macOS 15.x)
  • OpenClaw version: 2026.5.20 (brew install, baseline before patch)
  • Configuration: Dual agent setup (coder + researcher), 17 active plugins, Telegram + Discord + Line channels

Exact steps or command run after this patch

# Run all affected unit tests
cd /Users/samson1357924/projects/openclaw
npx vitest run src/commands/doctor/repair-sequencing.test.ts
npx vitest run src/commands/doctor/shared/plugin-dependency-cleanup.test.ts

# Verify doctor still works end-to-end (baseline, brew-installed)
openclaw doctor --fix --yes

Evidence after fix

Unit tests pass (12/12) — confirming code correctness:

✓ repair-sequencing.test.ts (10 tests)
  ✓ applies ordered repairs and sanitizes empty-allowlist warnings
  ✓ repairs managed npm plugin drift before missing plugin install repair
  ✓ migrates legacy OAuth sidecars before stale OAuth shadow cleanup
  ✓ emits Discord warnings when unsafe numeric ids block repair
  ✓ auto-enables newly installed configured plugins after doctor repair
  ✓ moves legacy Codex routes to canonical OpenAI before missing plugin install repair
  ✓ runs group allowFrom fallback migration after open-policy allowFrom repair
  ✓ does not remove deferred configured plugins during the package update doctor pass
  ✓ preserves configured plugins when their install repair fails
  ✓ preserves configured channels when their install repair fails

✓ plugin-dependency-cleanup.test.ts (2 tests)
  ✓ collects and removes legacy plugin dependency state roots
  ✓ removes dangling global plugin-runtime symlinks that point at legacy runtime deps

End-to-end doctor --fix runs successfully on real setup:

openclaw doctor --fix --yes
┌  OpenClaw doctor
◇  Doctor warnings (plugins.allow, channel configs)
◇  OAuth refresh errors
◇  Model auth
◇  Plugin registry: 17/97 enabled plugins indexed
◇  State integrity: 4 orphan agent dirs, 1 orphan transcript
◇  Cron: 11 jobs reviewed, normalized
◇  Doctor changes: cron store normalized, 1 dreaming job rewritten
◇  Security: plaintext secret config warning
◇  Skills status: Eligible: 91, Missing: 0
◇  Plugins: Loaded: 17, Disabled: 80, Errors: 0
◇  Bootstrap file size: AGENTS.md at 95% of limit
└  Doctor complete.

Code review passed (deepseek-v4-flash): APPROVE with no critical issues. All 3 Important items (test coverage, safety documentation, missing assertions) addressed in follow-up commits.

Observed result after fix

  • Sequential I/O (3 independent filesystem steps) → concurrent Promise.all: wall-clock reduces from sum to max of the three operations
  • 50+ plugin directory scans → 6 concurrent root-level scans with per-plugin parallelism across 3 roots × 2 sub-paths
  • All 12 tests pass (same as before, behavior preserved)
  • Error handling preserved: each function catches I/O errors internally, safety contract documented at call site
  • openclaw doctor --fix --yes completes successfully on real setup

What was not tested

  • End-to-end wall-clock measurement of the patched version on VPS (requires deploying the build)
  • Interaction with --deep mode (planned for Phase 1B)
  • Performance on HDD spinning disks (parallel I/O may cause contention; acceptable for infrequent CLI command)
  • Cross-machine regression testing (single Mac mini M2 environment)

…ected into config

Two-part fix:

A (onboarding-plugin-install.ts): add bundled root guard in
addPluginLoadPath(). Before writing a plugin path to
plugins.load.paths, check whether it resolves to OpenClaw's
bundled plugin directory via resolvePackagedBundledLoadPathAlias.
Bundled plugins are auto-discovered and do not need a config entry.

B (repair-sequencing.ts): move maybeRepairBundledPluginLoadPaths
to the end of the repair sequence so it runs after all plugin
install/enable/auto-enable mutations are complete. Without this,
plugin repair steps could re-add the bundled path after the
mid-sequence cleanup, leaving a dirty config to be persisted.

References: openclaw#85334
…ct flood

Repeated callGateway calls each created a fresh GatewayClient then
stopped it immediately. Each new client started WS exponential backoff
from 1s, so background agents polling sessions.list (~2/sec) never
let backoff converge to 30s, creating a sustained auth flood.

Fix: pool GatewayClients by (method + token + password) key.
acquirePooledClient() reuses a live client from the pool.
releasePooledClient() keeps the client alive for 10s TTL then cleans
up, letting WS backoff converge properly.

Also adds GatewayClient.isShutdown public getter for pool liveness
check without reaching into the private closed field.

References: openclaw#85333
- Add CLIENT_POOL_MAX_SIZE=64 to prevent unbounded Map growth
- Remove TTL-based cleanup (TTL race with in-flight requests)
- Pool entries live until disconnected; stale entries evicted on acquire
- Addresses PR openclaw#85462 review feedback from Argus
Phase 1A optimizations for openclaw#85333:

repair-sequencing.ts:
- Run cleanupLegacyPluginDependencyState, maybeRepairLegacyOAuthSidecarProfiles,
  and repairStaleOAuthProfileShadows in parallel via Promise.all
- These are filesystem-only operations with no config dependencies,
  so concurrent execution is safe

plugin-dependency-cleanup.ts:
- Parallelize per-plugin directory walks in collectLegacyExtensionDebris
  by mapping over pluginDirs with Promise.all instead of serial for loop
- Parallelize root-level calls (3 roots × 2 sub-paths = 6 concurrent reads)
  instead of serial iteration

All existing tests pass (10 repair-sequencing, 2 plugin-dependency-cleanup)
The events array asserted mock execution order under Promise.all,
which is an implementation detail. ChangeNotes ordering is already
verified deterministically (pushed after Promise.all resolves).
…lel branches in test

- Document Promise.all safety contract in repair-sequencing.ts
- Assert repairStaleOAuthProfileShadows call args in OAuth migration test
- Assert cleanupLegacyPluginDependencyState was called (all 3 branches)
- Convert plugin-dependency-cleanup mock from anonymous fn to vi.fn()
  so it's assertable
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime commands Command implementations size: L triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

Latest ClawSweeper review: 2026-05-23 00:40 UTC / May 22, 2026, 8:40 PM ET.

Workflow note: Future ClawSweeper reviews update this same comment in place.

How this review workflow works
  • 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.

Summary
The PR parallelizes parts of the doctor repair sequence and plugin dependency cleanup, changes bundled plugin load-path handling, wraps JSON reads with retries, and adds GatewayClient pooling.

Reproducibility: Partly: the linked doctor slowdown has reporter benchmarks, but I did not reproduce it live. The blocking PR regressions are high-confidence from source comparison between the PR head and current main.

PR rating
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Summary: The PR is not quality-ready because proof is insufficient and source review found blocking cleanup, gateway auth-boundary, and availability regressions.

Rank-up moves:

  • Rebase onto current main and preserve the existing cleanup target validation plus gateway abort/onAccepted semantics.
  • Remove or split the GatewayClient pooling and JSON retry changes unless they receive separate maintainer design review.
  • Add redacted patched-build openclaw doctor --fix before/after timing proof from a setup that exercises the reported slowdown.
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

Real behavior proof
Needs stronger real behavior proof before merge: The PR body includes terminal-style output, but it does not prove an after-fix patched build or timing improvement; the contributor should add redacted before/after patched-run output or an artifact, then update the PR body for a fresh ClawSweeper review.

Risk before merge

  • Merging this branch as-is could reintroduce unsafe recursive cleanup behavior that current main now guards against with realpath and symlink checks.
  • The GatewayClient pool can reuse a live connection across different URLs, TLS fingerprints, scopes, device identities, approval tokens, or protocol bounds because the pool key only includes method and shared auth strings.
  • The no-op pooled-client release can keep WebSocket connections and timers alive after one-shot CLI calls, and the branch is missing current-main abort/onAccepted/onSignalAbort behavior.
  • The linked performance issue identifies a CPU-heavy session snapshot path-validation bottleneck, while the PR mainly parallelizes I/O cleanup paths and does not prove patched wall-clock improvement.
  • The PR is based behind current main and is currently not mergeable, so resolving conflicts must preserve current cleanup safety and gateway abort contracts.

Maintainer options:

  1. Rebase and narrow to doctor performance (recommended)
    Update onto current main, keep the cleanup safety and gateway abort/lifecycle contracts, and limit this PR to the doctor repair performance change with focused tests and timing proof.
  2. Design gateway pooling separately
    If maintainers want pooled GatewayClients, handle it in a separate PR with a full connection-identity key, bounded lifecycle, abort semantics, and gateway-focused tests.
  3. Pause if the branch stays broad
    If the branch cannot be narrowed and proven, keep the linked performance issue open and supersede this PR with a smaller replacement.

Next step before merge
Needs contributor/maintainer rebase, narrowing, safety fixes, and real behavior proof; automation should not take over while the required proof depends on the contributor's real doctor setup.

Security
Needs attention: The diff has concrete filesystem-deletion and gateway authorization-boundary concerns that need repair before merge.

Review findings

  • [P1] Restore cleanup target validation before recursive removal — src/commands/doctor/shared/plugin-dependency-cleanup.ts:151-156
  • [P1] Include the full connection identity in the pool key — src/gateway/call.ts:53-54
  • [P1] Do not keep one-shot gateway clients alive indefinitely — src/gateway/call.ts:74-79
Review details

Best possible solution:

Rebase and narrow the branch to the doctor performance path, preserve current cleanup and gateway request contracts, split gateway pooling or JSON retry changes into separate reviewed work, and add redacted patched-build before/after doctor timing proof.

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

Partly: the linked doctor slowdown has reporter benchmarks, but I did not reproduce it live. The blocking PR regressions are high-confidence from source comparison between the PR head and current main.

Is this the best way to solve the issue?

No: the doctor parallelization may be useful, but the branch mixes unrelated gateway pooling, JSON retry, and load-path changes and does not preserve current safety contracts. A narrower rebased PR with separate gateway design review is the maintainable path.

Label justifications:

  • P1: The PR is tied to a real doctor performance regression but currently carries blocking gateway availability and cleanup safety regressions.
  • merge-risk: 🚨 compatibility: The branch is behind current main and would drop current gateway abort/onAccepted behavior and cleanup safety contracts unless carefully rebased.
  • merge-risk: 🚨 security-boundary: The gateway pool key omits security-relevant connection identity fields and cleanup changes affect recursive filesystem deletion boundaries.
  • merge-risk: 🚨 availability: The no-op gateway release can keep one-shot CLI WebSocket clients and timers alive, causing commands to hang or leak background work.
  • rating: 🧂 unranked krab: Current PR rating is 🧂 unranked krab because proof is 🧂 unranked krab, patch quality is 🧂 unranked krab, and The PR is not quality-ready because proof is insufficient and source review found blocking cleanup, gateway auth-boundary, and availability regressions.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body includes terminal-style output, but it does not prove an after-fix patched build or timing improvement; the contributor should add redacted before/after patched-run output or an artifact, then update the PR body for a fresh ClawSweeper review.

Full review comments:

  • [P1] Restore cleanup target validation before recursive removal — src/commands/doctor/shared/plugin-dependency-cleanup.ts:151-156
    The PR head returns raw cleanup paths and removes each existing target with fs.rm, but current main validates names, realpaths, cleanup roots, and symlink roots before removal. Without preserving those checks, doctor --fix can delete arbitrary configured or symlinked directories outside OpenClaw cleanup roots.
    Confidence: 0.93
  • [P1] Include the full connection identity in the pool key — src/gateway/call.ts:53-54
    Pooling only by method/token/password can reuse a GatewayClient created for a different URL, TLS fingerprint, scopes, approval token, device identity, protocol range, or instance id. That can send later authenticated calls over the wrong gateway connection and scope set.
    Confidence: 0.9
  • [P1] Do not keep one-shot gateway clients alive indefinitely — src/gateway/call.ts:74-79
    releasePooledClient is a no-op, so calls that previously stopped their GatewayClient now leave WebSocket reconnect timers alive after the promise settles. That can keep CLI commands running and also drops current-main request abort/accepted callback behavior unless the rebase preserves it.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.9

Security concerns:

  • [high] Unsafe recursive cleanup boundary — src/commands/doctor/shared/plugin-dependency-cleanup.ts:151
    The PR head removes collected cleanup paths without current-main realpath containment and symlink-root checks, which can cross filesystem boundaries during doctor --fix.
    Confidence: 0.91
  • [high] Gateway connection identity is under-keyed — src/gateway/call.ts:53
    Sharing GatewayClients across calls without URL, TLS, scopes, approval token, and device identity in the key can cross auth and transport boundaries.
    Confidence: 0.88

What I checked:

  • PR head removes cleanup target validation before removal: The PR head collects raw string targets and then recursively removes every existing target with fs.rm, without the current-main CleanupTarget filtering, realpath containment, symlink-root refusal, or unexpected-name checks. (src/commands/doctor/shared/plugin-dependency-cleanup.ts:151, ea50ec331526)
  • Current main has cleanup safety gates and tests: Current main validates cleanup targets with filterLegacyStaleRootCandidates, resolveSafeRemovalTarget, realpath containment, and symlink-root protections before fs.rm; adjacent tests cover arbitrary explicit roots and symlinked roots resolving outside OpenClaw roots. (src/commands/doctor/shared/plugin-dependency-cleanup.ts:263, 743caedb052a)
  • Gateway pool key omits connection identity: The PR pools clients only by method, token, and password even though the client is constructed with url, TLS fingerprint, scopes, approval runtime token, device identity, protocol bounds, client mode, and instance id. (src/gateway/call.ts:53, ea50ec331526)
  • Gateway pool release is a no-op: The PR no longer stops the GatewayClient when a call settles, so one-shot CLI calls can leave WebSocket reconnect timers alive and reused beyond the request lifetime. (src/gateway/call.ts:74, ea50ec331526)
  • Current main preserves abort and teardown semantics: Current main rejects pre-aborted requests, forwards signal and onAccepted, runs onSignalAbort on the active connection, and stops the client before settling; tests cover the active abort hook and pre-request abort behavior. (src/gateway/call.ts:691, 743caedb052a)
  • PR proof does not demonstrate patched performance: The PR body includes unit-test output and a real doctor command transcript, but the transcript is described as a brew-installed baseline and lacks patched-build timing or before/after wall-clock proof for the reported VPS slowdown. (ea50ec331526)

Likely related people:

  • @steipete: Recent history shows repeated doctor, plugin, gateway, auth, and test refactors across the affected surfaces. (role: recent area contributor; confidence: medium; commits: f8f98c116e7b, b7d362ddbb85, 812f96cf24e2; files: src/commands/doctor/repair-sequencing.ts, src/commands/doctor/shared/plugin-dependency-cleanup.ts, src/gateway/call.ts)
  • @vincentkoc: Recent history includes doctor performance fast paths, plugin/gateway cold-path trimming, and auth/gateway compatibility work near the PR's stated problem area. (role: recent performance and compatibility contributor; confidence: medium; commits: 66e06b50bac3, 1169dd703962, 3362cccc20a9; files: src/commands/doctor/repair-sequencing.ts, src/plugins, src/gateway/call.ts)
  • @gumadeiras: Recent history shows adjacent gateway auth test reuse and plugin/setup test slimming, which are relevant to evaluating pooling and plugin cleanup risks. (role: adjacent gateway/plugin test contributor; confidence: low; commits: 5af1a51f8e67, 110f8bd2e1e2, 3ca8ad38459c; files: src/gateway, src/plugins, src/commands/doctor/shared/plugin-dependency-cleanup.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 743caedb052a.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels May 22, 2026
@clawsweeper

clawsweeper Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@samson1357924

Copy link
Copy Markdown
Contributor Author

Superseded by #85670 (cleaner branch, adapted for current upstream code)

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

Labels

commands Command implementations gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant