Skip to content

fix: keep session writes responsive during workspace cleanup - #202874

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-libuv-pool-bulk-unlink-20260919
Nov 21, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-libuv-pool-bulk-unlink-20260919

Conversation

@steipete

@steipete steipete commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Recursive template and checkout cleanup can occupy all four default libuv filesystem workers in the Gateway. Slow unlinks then delay unrelated session filesystem operations. Route bulk tree removal through the existing native filesystem child owner and its shared two-child budget.

User Impact

Session filesystem operations retain access to the Gateway pool during bulk cleanup. Cleanup remains awaited before path reuse, preserving rollback/error behavior. No configuration, schema, cache, or threadpool-size change.

Why This Change Was Made

The owner cutover covers template replacement/install debris, partial clone rollback, initial projection replacement, exact-restore staging, and materialized checkpoint results. Missing-registration eviction already runs in the Git worker and now removes synchronously there. Normal/orphan GC already uses paced child deletion; copy rollback/provision cleanup already runs inside its worker/child. Container cleanup stays with the engine. Bounded single-file/empty-directory cleanup stays local. Worker bundle installation is a separate follow-up, not part of this managed-workspace path.

The duplicate template removal helper disappears. Production delta: 29 additions / 27 deletions, net +2 LOC; the additional staged-result import accounts for growth. No new helper or service. Rename-aside is unnecessary for isolation and would require a new detached cleanup lifecycle for immediately reused paths; retired checkpoint captures retain their existing lifecycle.

Evidence

Two existing real-flow regressions reject recursive main-process cleanup: generated template install debris and materialized checkpoint scratch. Each fails before its fix and passes afterward. The initial 157 focused tests passed. CI then exposed three stale cleanup test seams: PR acquisition observation, publication cleanup failure injection, and a retired-capture gate accidentally blocking newly migrated payload cleanup. The repair targets the native owner/artifact and preserves guest-resume, rollback, warning, and recovery-ref assertions. All six failing cases now pass locally (163 focused cases passed across the lane).

Independent Codex reviews of production, proof harness, staged-owner cutover, and the test repairs are scoped-clean at P0–P2; reviewers did not run tests. ClawSweeper reviewed head 008471117c3a2e9bd0e1e207627fb540c72e1847 with zero findings. Final test-only head is 4dec9dc37d00597b5746024a978b93fb4b0a820e. Exact-head CI run 44865486075 is green, including the aggregate gate. ClawSweeper reviewed that head with zero code findings and one decision item. The performance-owner acceptance is now recorded below; a re-review is requested to close that item before native landing.

pnpm check:changed --staged completed for production and the test repair. The final test repair's one redundant string conversion was removed; targeted lint/format pass. Only inherited dead-export findings remain. Exact parent 2b5f1a88ba81e03d51010065c836f48490ebb498 reproduces the same five production/three full-tree findings. Introducing PRs: #202654 (prepareGatewayPublicationTransportV1), #201615 (canReadApprovalSession, authorizeSessionPermissionModeChange), #202534 (checkSessionWorkspaceFileLinks, and removal of the last external production openSessionWorkspaceManagedArtifact consumer). These are reported main regressions, not ignored noise. The normal PR CI run 44862605420 passed its other planned checks and failed only the test seams above; manual run 44861883514 additionally planned/reproduced the dead-export failure.

Synthetic scale result

Final head changes only three test/support files relative to the measured head. Measured on frozen production/proof head 008471117c3a2e9bd0e1e207627fb540c72e1847: real Gateway WebSocket sessions.patch and Gateway async file writes during real projection replacement. Fresh 62,000-file / 1,142,784,000-byte trees per sample. Synthetic database: 48.06 GiB, 5,000 session records, 271,424 transcript events across 1,724 sessions. No production data. APFS with injected slow unlink, not a btrfs result. Two warmups, two A/A controls, five serial interleaved A/B pairs, then the injected pair. Startup/fixture construction are outside timing; normal background integrity verification remained active. Source-mode Node child startup is included.

The acceptance rule was recorded before measurement: injected bulk-removal occupancy must become zero Gateway pool workers, with patch/file-write maxima below 250 ms; adverse cost movements above 20% require explicit performance-owner acceptance.

Injected one-second stall: patch maximum 1,441.92 → 13.89 ms; filesystem-write maximum 1,388.41 → 4.75 ms. Trace: four Gateway TIDs overlap for 1.00 s before; one child TID blocks afterward, with zero delayed Gateway TIDs. Bulk-removal occupancy 4/4 → 0/4. The candidate's ten no-removal control patches had a 28.24 ms maximum (4.33 ms median), versus 13.89 ms maximum (4.58 ms median) during removal. This passes the declared injected acceptance rule.

Metric (5 paired runs) Before median / p95 [range] After median / p95 [range]
Owner wall ms 2373.47 / 2504.57 [1877.36–2504.57] 4229.62 / 7304.62 [3578.23–7304.62]
Gateway CPU ms 7505.88 / 8306.43 [6346.23–8306.43] 2942.44 / 4343.20 [1967.62–4343.20]
Main-thread CPU ms 972.84 / 1110.38 [775.79–1110.38] 1016.55 / 1533.44 [779.41–1533.44]
Child CPU ms 0.00 / 0.00 [0.00–0.00] 3805.50 / 6491.70 [3423.45–6491.70]
Gateway + child CPU ms 7505.88 / 8306.43 [6346.23–8306.43] 7226.36 / 10834.91 [5391.07–10834.91]
Main V8 allocated MB 150.49 / 162.61 [141.44–162.61] 273.05 / 293.60 [214.04–293.60]
Main + child V8 allocated MB 150.49 / 162.61 [141.44–162.61] 768.60 / 784.67 [718.72–784.67]
Patch maximum ms 1102.02 / 1378.19 [946.42–1378.19] 123.20 / 964.97 [8.24–964.97]
Patch p95 ms 647.65 / 905.64 [49.88–905.64] 8.05 / 67.24 [6.18–67.24]
FS-write maximum ms 1306.64 / 1489.38 [985.67–1489.38] 34.27 / 44.55 [3.81–44.55]
FS-write p95 ms 145.28 / 581.68 [32.67–581.68] 1.12 / 9.19 [0.26–9.19]
Completed patches 24.00 / 45.00 [21.00–45.00] 231.00 / 266.00 [182.00–266.00]
Removal children 0.00 / 0.00 [0.00–0.00] 3.00 / 3.00 [3.00–3.00]

A/A aa1: owner 7482.11 ms; Gateway CPU 18950.30 ms; main CPU 1404.57 ms; allocation 165.32 MB; patch max 4704.39 ms; write max 4562.01 ms; control max 5460.82 ms; load [35.4375, 29.8876953125, 25.32080078125].

A/A aa2: owner 2500.33 ms; Gateway CPU 8446.70 ms; main CPU 1040.30 ms; allocation 147.73 MB; patch max 1171.61 ms; write max 1123.80 ms; control max 2560.50 ms; load [24.85205078125, 28.60009765625, 25.3876953125].

Measured A/B load ranges: [9.8798828125, 22.68603515625]

The p95 above is nearest-rank across five per-run values (therefore the maximum); individual request distributions are retained in the measurement output. One normal candidate patch reached 964.97 ms while its fs-write maximum was 13.04 ms; it remains in the table. Isolation does not eliminate shared-disk or other session latency. A/A controls expose substantial host/startup-maintenance variation; no samples were discarded from the declared campaign.

ACCEPTED — Lead decision by the Team perf-loop lead (an agent acting under Peter's standing unattended instruction), not Peter's.

The lead accepts cleanup wall +78% (2.37→4.23 s, background, awaited only before path reuse), main V8 allocation +81% and main CPU p95 +38% (largely the ~10× more foreground patches that now complete instead of queuing behind pool-blocking unlinks), and main+child allocation +411% (≈0.5 GB in three short-lived source-mode removal children). Compiled-release startup is expected to be cheaper and was not measured. Median total CPU fell 4%. The recorded CPU-tail costs and source-mode limitations are accepted in exchange for bulk-removal Gateway pool occupancy 4/4→0/4 and patch/fs-write maxima 1,442/1,388 ms→13.9/4.7 ms during cleanup. This is the performance-owner decision for landing this PR.

The canonical synthetic seed failed its final WAL checkpoint after committed writes. The retained database passed independent read-only quick_check; canonical checkpoint/close succeeded, and the benchmark used normal Gateway admission/integrity checking. It is a partially populated synthetic seed, not a claim that the originally requested logical transcript byte target completed. Earlier setup failures and concurrent-seed diagnostic profiles are excluded from this primary campaign and retained in the lane report.

Rerun the committed workload using synthetic inputs only:

git show 2b5f1a88ba81e03d51010065c836f48490ebb498:src/gateway/worker-environments/local-workspace-checkout.ts > src/gateway/worker-environments/local-workspace-checkout.baseline.ts
cc -dynamiclib -o "$PROOF/delay.dylib" scripts/perf/bulk-unlink-delay.c
node --import ./scripts/tsx.mjs scripts/perf/bulk-unlink-gateway-measure.ts \
  --output "$PROOF/run" --files 62000 --sessions 5000 --pairs 5 \
  --baseline-module src/gateway/worker-environments/local-workspace-checkout.baseline.ts \
  --delay-library "$PROOF/delay.dylib" \
  --fixture-state "$SYNTHETIC_STATE" --fixture-tree "$SYNTHETIC_TREE"

The driver can generate synthetic inputs when reuse options are omitted; large seeding is expensive. On Linux compile the hook with cc -shared -fPIC -o "$PROOF/delay.so" scripts/perf/bulk-unlink-delay.c -ldl and pass that library. The driver selects LD_PRELOAD/DYLD_INSERT_LIBRARIES and fixes UV_THREADPOOL_SIZE=4 only in disposable proof processes.

@clawsweeper

clawsweeper Bot commented Nov 21, 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 scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 21, 2026
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 21, 2026
@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR moves bulk workspace cleanup into existing bounded background execution owners so session filesystem operations remain responsive.

Example: Replace a 62,000-file projection while injecting a one-second unlink stall.

  • Before: Bulk removal occupies all four Gateway filesystem workers; session patch latency reaches 1,441.92 ms.
  • After: Removal occupies no Gateway filesystem workers; session patch latency reaches 13.89 ms.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused owner reuse, real Gateway measurements, and successful exact-head CI support readiness within the accepted APFS source-mode measurement limits.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The recorded APFS campaign runs real Gateway WebSocket session patches alongside production projection replacement, with five interleaved pairs and injected unlink traces showing Gateway removal occupancy falling from four workers to zero; production and proof code are unchanged at the final head, and source-mode and host-variation limits are disclosed and accepted.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Session reads and writes stall while workspace cleanup monopolizes the Gateway filesystem pool.
Reason: The measured pool isolation addresses the stated problem, and the maintainer has recorded acceptance of the adverse resource costs.

Merge readiness

✅ Ready for maintainer review

The recorded performance-owner acceptance resolves the previous decision item; no actionable findings remain on the reviewed head.

Priority: P2
Reviewed head: 4dec9dc37d00597b5746024a978b93fb4b0a820e

Before merge

None.

Findings

None.

Agent review details

How this fits together

Managed-workspace owners request deletion of disposable or interrupted checkout trees, await completion, and then reuse paths or finish reconciliation.

flowchart TD
  A[Workspace lifecycle owners] --> B[Native filesystem owner]
  B --> C[Shared two-child budget]
  C --> D[Supervised removal child]
  D --> E[Completion receipt]
  E --> A
  F[Session requests] --> G[Gateway filesystem pool]
Loading

Technical review

Best possible solution:

Use the existing bounded filesystem child for bulk cleanup while preserving path-reuse ordering, rollback custody, and best-effort staging cleanup.

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

Current-main source retains the shared-pool removal path, and the supplied baseline campaign demonstrates filesystem-worker saturation and delayed session operations; no target code was executed during this review.

Is this the best way to solve the issue?

The change is the smallest complete owner cutover: it reuses existing supervision and concurrency limits, removes duplicate template-removal logic, and avoids a detached cleanup lifecycle.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 951befe82d5d.

Provenance checked

  • Native filesystem child removal keeps the original intent (cd20cf7: Keep template retirement off the Gateway heap through supervised synchronous child removal.)
  • Template cleanup and projection preparation keeps the original intent (2c4413a: Reduce Gateway filesystem stalls while retaining authority, exclusion, and accepted-work settlement.)
  • Clone rollback custody keeps the original intent (23fb1c0: Preserve work during creation and cleanup races through allocation authority and original Git registration.)
  • Exact restore staging keeps the original intent (1520154: Restore exact detached checkout state without losing staged data or recovery custody.)
  • Materialized-result cleanup keeps the original intent (1d3d65e: Disposable scratch cleanup failures must preserve committed results, original publication errors, and recovery references.)
  • Missing-registration eviction keeps the original intent (3b16db7: Perform claimed worktree eviction through the existing background Git worker.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cd20cf7 adds src/agents/worktrees/filesystem-native.ts:143 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cd20cf710114; files: src/agents/worktrees/filesystem-native.ts)
  • Jason (Json): Raw commit 1520154 adds src/agents/worktrees/snapshot-restore-exact.ts:289 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 15201542a535; files: src/agents/worktrees/snapshot-restore-exact.ts)

PR surface

Source +2, Tests +18, Docs +4, Other +506. Total +530 across 17 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 29 27 +2
Tests 6 25 7 +18
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 3 506 0 +506
Total 17 564 34 +530

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.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Bulk workspace cleanup can delay unrelated session operations under filesystem pressure, with a focused isolation fix and demonstrated benefit.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (3 earlier review cycles)
  • reviewed 2026-11-21T02:52:07.590Z sha 0f733d3 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-21T03:40:12.174Z sha 0084711 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-21T04:25:19.264Z sha 4dec9dc :: blocked before merge. :: none

Reviewed November 20, 2026, 11:42 PM ET / November 21, 2026, 04:42 UTC (Revision 4).

Use the existing bounded filesystem child for materialized checkpoint trees. Preserve awaited best-effort cleanup and extend the real materialization regression. Mock the cleanup subprocess in the simulated Windows Git environment contract test.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review final code head 0084711. Bulk template, checkout, restore, and checkpoint staging cleanup now uses the existing bounded native child; the missing-registration eviction fallback stays synchronous inside its existing Git worker. Focus on lifecycle/authority preservation and shared-pool isolation. Local Codex review is clean and 157 focused tests pass. Full-size synthetic performance evidence and exact-head CI are still pending; this remains a draft until those gates and performance-owner acceptance are complete.

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete marked this pull request as ready for review November 21, 2026 03:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T04:21:25.800676Z 4dec9dc 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.

Keep PR acquisition pause checks and cleanup-failure injection on the native removal boundary. Restrict the deferred capture fixture to retired capture artifacts so checkpoint payload cleanup can settle.
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review final head 4dec9dc37d00597b5746024a978b93fb4b0a820e. The previous head had zero findings. CI identified three stale test seams after the cleanup-owner cutover: PR acquisition observation, scratch-cleanup failure injection, and deferred retired-capture gating. The six failing cases now pass locally; final scoped Codex review is clean at P0–P2. Targeted typechecks, lint, and format pass; the unchanged dead-export failures reproduce on the exact parent with introducing PRs recorded in the body.

The PR body now includes the completed 62k-file/48.06 GiB synthetic campaign, five A/B pairs, A/A controls, injected unlink occupancy, CPU/allocation costs, and limitations. Production/proof sources are unchanged from measured head 008471117c3a2e9bd0e1e207627fb540c72e1847. Performance-owner cost acceptance remains pending; no merge has been submitted.

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

Item 1 — resolved by the performance owner's recorded acceptance in the PR body.

Lead decision by the Team perf-loop lead (an agent acting under Peter's standing unattended instruction), not Peter's. The lead explicitly accepts the reported cleanup-wall, allocation, and CPU-tail costs and the source-mode measurement limitations for the demonstrated Gateway pool isolation and foreground latency improvement. Compiled-release startup was not measured.

The accepted ownership boundary is unchanged: bounded child removal, awaited projection replacement, and materialized result cleanup. Exact-head CI run 44865486075 is green. No code changed after that proof.

@clawsweeper re-review

Please verify the recorded acceptance and clear the single decision item on final head 4dec9dc37d00597b5746024a978b93fb4b0a820e.

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. label Nov 21, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Nov 21, 2026
@steipete
steipete merged commit 633cd29 into main Nov 21, 2026
162 of 164 checks passed
@steipete
steipete deleted the steipete/perf-micro-libuv-pool-bulk-unlink-20260919 branch November 21, 2026 04:47
@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 22, 2026
…w#202874)

* fix: keep session writes responsive during workspace cleanup

* test: make bulk cleanup measurements reuse synthetic fixtures

* fix: isolate checkpoint staging cleanup

Use the existing bounded filesystem child for materialized checkpoint trees. Preserve awaited best-effort cleanup and extend the real materialization regression. Mock the cleanup subprocess in the simulated Windows Git environment contract test.

* test: observe bulk cleanup through its native owner

Keep PR acquisition pause checks and cleanup-failure injection on the native removal boundary. Restrict the deferred capture fixture to retired capture artifacts so checkpoint payload cleanup can settle.
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix: keep agent temporary files in owned scratch

* fix: preserve sandbox temp access and queued isolation custody

(cherry picked from commit f91bc99)

Release adaptation: keep the staged #202815 Git shim implementation and independently assert both Git shim execution and writable owned temp in its merged Docker/Podman fixture. Use the beta.3 isolated custody configuration (896f33d52174), not ambient sandbox inventory.

Companions: #193677 scratch expiry owner is present (99ba844); #202815 is present-equivalent (7d33d1a). #202122 is independent Git/scratch clone reclamation, #202428 is CLI history ownership, #202644 is host file-write authority, and #202874 is workspace cleanup scheduling; none prerequisite. Other later same-path commits concern separate template, sandbox, prompt, sharing, or run-lifecycle policy; see the lane companion audit.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a4070bc5b669308210b62a0b80b92c16af768b34)
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L 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.

1 participant