Skip to content

fix: keep recently used session worktrees from idle cleanup - #201333

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-cron-cleanup-removes-live-session-worktree-20260919
Nov 18, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-cron-cleanup-removes-live-session-worktree-20260919

Conversation

@steipete

@steipete steipete commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A session can use an old managed worktree without refreshing its recorded activity. Once the run finishes, idle cleanup can still treat the checkout as unused since creation. Returning to a removed checkout also recreated an empty directory before reporting the removal.

User Impact

Recently used worktrees retain their idle-retention window. Returning to an already removed worktree keeps its path absent and reports the worktree ID alongside the existing Restore guidance. Previously removed worktrees still require explicit restoration.

Why This Change Was Made

Actual run boundaries now record activity through the existing registry writer: native/plugin workspace preparation, run-lease acquisition, and final lease release. The persisted timestamp coalesces updates over five minutes across processes, using existing live-row and observed-timestamp conditions. There is no new cache, configuration, schema, or per-tool-call write. Directory creation belongs to workspace preparation after binding validation; the earlier duplicate mkdir is removed.

The explicit worktree acquire service already recorded activity, but ordinary execution did not use it. GC also considers session-owner activity and live custody, so this change does not imply that every historical removal was caused by the timestamp omission.

Production delta: +30 lines, including the shared bounded-write operation and its callers, with two redundant lines deleted. Tests add 67 net lines; the rerunnable synthetic measurement script adds 200 lines.

Evidence

  • An old checkout used yesterday is collected on the base after its run lease ends. The regression passes with the fix, including coalesced short runs, refresh at final release after a long run, and eventual collection after becoming idle again.
  • A real Gateway test reproduces the removed path reappearing after chat refusal; it stays absent with this change, and the diagnostic contains the worktree ID.
  • An existing full Gateway/model-turn test now ages the record before sending chat and verifies that successful execution refreshes activity without invalidating run custody.
  • 165 focused tests pass across workspace preparation, run leases, GC/capacity, snapshot retirement, cron cleanup, embedded attempts, and the two Gateway product tests. Codex autoreview is clean through P2.
  • pnpm check:changed on the final committed head passes every gate except two unrelated export failures. Those failures reproduce on clean exact parent 0aafe6691b818c24ac00a2172e57819b21632554: OPENAI_CODEX_CLIENT_VERSION_FLOOR was introduced unused in production by 1680f54504807 (fix(openai): new ChatGPT subscription models missing until an OpenClaw release #201130); the last barrel consumer of watchSelectedAgent was removed by d33473385623a (improve: choose an automation's model and reasoning with the chat composer's pickers #201218). These are main regressions. Benchmark lint and all other checks pass on this head.
  • Synthetic fixture is prepared: 10,000 canonical sessions, a 35 GiB agent DB, and 62,000 files / 1.14 GB checkout. Two baseline A/A controls and five alternating A/B pairs are complete. All candidate runs recorded first use and kept the timestamp unchanged through 20 subsequent short runs; every baseline run left it at 1. Local filesystem is APFS; btrfs qualification is unavailable because the configured remote runner lacks credentials.

Measurement acceptance: recent use must advance activity, the next 20 short runs must keep that timestamp, and coalesced owner cost is compared with A/A noise; the first required durable write is reported separately. Exact-head CI 44350917733 passed for aace1b071df88f1f157ad48c87bd002458b2253d, including openclaw/ci-gate. Final-head ClawSweeper review reports zero findings and zero open items. Runtime proof uses an in-process real Gateway/agent runner with a synthetic provider; no standalone shipped-CLI or live external-provider proof is claimed.

Synthetic owner measurements

Warm filesystem caches; setup/imports excluded. Each sample is a fresh Node 26.12.1 process. Coalesced values are per operation (20 operations per sample). CPU includes process threads, excludes Git/state-broker children; allocation is main-isolate V8 allocation. The first write is necessary new durable work, not a speedup.

Owner/phase Arm (n) Wall median / p95 (ms) CPU median (ms) Main allocation median (KiB)
lease/first-write base (5) 31.997 / 48.548 33.946 5676.8
lease/first-write candidate (5) 32.938 / 43.824 35.631 5966.8
lease/first-write aa (2) 32.351 / 32.981 34.142 4898.7
lease/coalesced base (5) 26.173 / 27.106 9.713 2893.7
lease/coalesced candidate (5) 27.652 / 30.125 11.301 2698.8
lease/coalesced aa (2) 26.693 / 27.098 9.710 2799.9
workspace/first-write base (5) 3.184 / 3.856 6.769 667.4
workspace/first-write candidate (5) 5.373 / 5.797 24.781 1223.2
workspace/first-write aa (2) 3.773 / 3.852 10.041 677.7
workspace/coalesced base (5) 1.663 / 1.969 4.224 885.1
workspace/coalesced candidate (5) 1.641 / 2.253 3.059 927.1
workspace/coalesced aa (2) 1.597 / 1.610 2.951 950.5

The first workspace write adds 2.19 ms median wall, 18.01 ms process CPU and 556 KiB main allocation; it occurs at most once per five minutes through these boundaries. Coalesced lease wall/CPU increased 5.7%/16.3%; main allocation decreased 6.7%. Coalesced workspace wall held steady, CPU decreased, and allocation increased 4.7%. This correctness fix explicitly pays for recording use; no claim of an overall speedup. A/A controls and all raw samples are retained locally; five-sample p95 is the maximum sample.

Reproduction: seed with scripts/perf/agent-startup-inspection.ts seed --state-dir <new-root>/state --gib 35; prepare using scripts/perf/worktree-activity-measure.ts --prepare <root>; then run <root> <new-result.json> under node --expose-gc --import ./scripts/tsx.mjs. For baseline, OPENCLAW_BENCH_BASELINE_DIR points to the three owner modules (registry.ts, run-lease.ts, workspace-sandbox.ts) extracted from 0aafe6691b818c24ac00a2172e57819b21632554.

CI repair

The first CI run found one PR-caused test fixture failure: the image-admission test used the removed early mkdir as a stop hook. The final test-only follow-up stops through its existing admission callback after evaluating the real image policy. Both image-support cases pass locally; the filesystem spy, mock-order assertion, and unnecessary mock cleanup are removed. Codex autoreview of the repair is clean. Production code and the measured owner files are unchanged from the measured head. The failed run is retained as evidence; fresh exact-head CI and ClawSweeper re-review both completed successfully. No CI rerun or inherited-failure exception was used for this PR-caused fixture failure.

@clawsweeper

clawsweeper Bot commented Nov 18, 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: M labels Nov 18, 2026
@steipete
steipete marked this pull request as ready for review November 18, 2026 16:17
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 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-18T16:48:27.416015Z aace1b0 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.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: aace1b071df88f1f157ad48c87bd002458b2253d
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/workspace-sandbox.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

The final head is 2ee0ecf28bdd4f9e943659761261a3578592aef1. Please check the shared activity writer, run admission/final lease release, and native/plugin workspace preparation. The PR now contains the completed synthetic measurements, exact-base regression proof, and attribution of the two inherited unused-export failures.

@clawsweeper

clawsweeper Bot commented Nov 18, 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Record managed-worktree activity at execution boundaries and prevent refused turns from recreating removed checkout directories.

Example: A nine-day-old session checkout is used yesterday and idle cleanup runs today.

  • Before: The stale worktree timestamp can leave the checkout eligible for cleanup after its run ends.
  • After: Run activity refreshes the timestamp, preserving the checkout's idle-retention window.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused patch has no identified correctness defect, but the required shipped-entry-point proof is absent; existing worktrees.last_active_at storage and schema remain unchanged, requiring no migration.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A recently used session checkout can still look idle, and returning to a removed checkout can recreate an empty directory.
Reason: The maintainer-authored direction restores the intended retention behavior while preserving explicit restoration and existing custody checks.

Merge readiness

✅ Ready for maintainer review

This PR addresses a concrete worktree-retention bug; no actionable introduced defect was found, including in the admission-test repair.

Priority: P2
Reviewed head: aace1b071df88f1f157ad48c87bd002458b2253d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted terminal output or logs from an isolated shipped Gateway showing a resumed old checkout surviving idle cleanup after the turn ends and a removed checkout remaining absent after refusal; redact credentials, IPs, phone numbers, and non-public endpoints.
Agent review details

How this fits together

Agent workspace preparation and run leases feed activity into the shared SQLite worktree registry, which cleanup reads to determine idle eligibility.

flowchart TD
  A[Session turn] --> B[Workspace preparation]
  A --> C[Run lease lifecycle]
  B --> D[Registry activity writer]
  C --> D
  D --> E[SQLite worktree registry]
  E --> F[Idle cleanup]
Loading

Technical review

Best possible solution:

Keep activity publication in the existing registry worker and directory creation after the existing removed-binding validation.

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

Current-main source shows the missing execution-boundary timestamp updates and premature mkdir; the submitted regressions target both paths, but this read-only review ran no tests.

Is this the best way to solve the issue?

The patch fixes the producer through existing registry and workspace owners, removes the duplicate mkdir, and adds no competing state or lifecycle owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Run leases and registry writes keeps the original intent (fix(agents): lease session worktrees during runs #103263: Shared leases protect active checkouts; subsequent worker migration placed registry persistence with the existing asynchronous transaction owner.)
  • Removed-worktree refusal keeps the original intent (fix: explain how to recover removed session worktrees #200691: Removed unarchived sessions must fail before sandbox preparation and require an explicit Restore action.)
  • Early dispatch directory creation changes intended behavior with a stated reason (cbcc1df: The dispatch refactor carried existing preparation behavior forward; the PR explains removing this duplicate mkdir so workspace validation precedes directory creation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 7244ad2 adds src/agents/workspace-sandbox.ts:153 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7244ad2cb3c2; files: src/agents/workspace-sandbox.ts)
  • Yuval Dinodia: Raw commit 7cd2e48 adds src/agents/worktrees/run-lease.ts:82 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7cd2e482d16b; files: src/agents/worktrees/run-lease.ts)

PR surface

Source +30, Tests +67, Docs +1, Other +200. Total +298 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 34 4 +30
Tests 5 80 13 +67
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 1 200 0 +200
Total 11 315 17 +298

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 test growth Production +34/-4; tests +80/-13; measurement tooling +200 Production growth adds one reused activity operation; tests protect distinct preparation, lease, and Gateway boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Recently used session checkouts can become eligible for idle removal after execution ends, causing avoidable restoration work.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab 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-18T16:27:25.778Z sha 2ee0ecf :: needs maintainer review before merge. :: none

Reviewed November 18, 2026, 11:53 AM ET / 16:53 UTC (Revision 2).

@steipete
steipete enabled auto-merge (squash) November 18, 2026 16:39
@steipete
steipete disabled auto-merge November 18, 2026 16:42
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review final head aace1b071df88f1f157ad48c87bd002458b2253d. Your previous report had zero findings/open items. The sole follow-up repairs the CI-discovered admission test fixture: run-attempt-dispatch.input.test.ts:38-55 now interrupts through its admission callback after checking the actual image policy, instead of mocking the removed early mkdir. Both cases pass locally and independent Codex autoreview is clean. Production code, owner measurements, and the worktree/Gateway regression proofs are unchanged. The PR body records the failed CI run and repair.

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit f5d35bc into main Nov 18, 2026
130 checks passed
@steipete
steipete deleted the steipete/perf-micro-cron-cleanup-removes-live-session-worktree-20260919 branch November 18, 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 19, 2026
…#201333)

* fix(worktrees): retain recently used session checkouts

* test(agents): decouple admission proof from workspace creation
steipete added a commit that referenced this pull request Nov 19, 2026
Replace the workspace mkdir barrier left stale by #201333 with the real transcript-target preparation boundary. Preserve both admission closure and replacement checks before routing publication and backend dispatch.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
…2068)

Replace the workspace mkdir barrier left stale by openclaw#201333 with the real transcript-target preparation boundary. Preserve both admission closure and replacement checks before routing publication and backend dispatch.
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
…#201333)

* fix(worktrees): retain recently used session checkouts

* test(agents): decouple admission proof from workspace creation

Release adaptation: Preserve reviewed individual adaptation; source bytes unchanged.

(cherry picked from commit f5d35bc)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
Replace the workspace mkdir barrier left stale by #201333 with the real transcript-target preparation boundary. Preserve both admission closure and replacement checks before routing publication and backend dispatch.

(cherry picked from commit 200bd90)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 1b9ddd1bd4ffe007a47407815e69118759b4fad6)
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
* fix(worktrees): retain recently used session checkouts

* test(agents): decouple admission proof from workspace creation

(cherry picked from commit f5d35bc)

Release adaptation: reuse the beta.3 adaptation aef0b19dc08b for the stable workspace owner: add existing reader/error imports and the minimal #200691 removed-checkout preflight so activity marking never recreates a removed checkout. Omit only the changed assertion in the Gateway test file absent on this branch; retain existing Gateway readiness and owner coverage.

Companions: #202074 is selected next. #202068 is present-equivalent (5631d96); #202204 changes later main-only GC owner-census behavior; #203057 is an independent probe optimization. Other later overlap concerns unrelated worktree refresh/reclamation, policy, restore UX, or the later absent removed-checkout fixture; not prerequisites (enumerated in lane audit).

Release adaptation: reuse the sibling path-specific realpath spy and no-recreation regression (abce9babd5cab). The original one-shot spy closed authority at the preflight read instead of the target workspace boundary.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit e3495dac6afc80bd3fe36110008dec96013d2514)
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Baseline adaptation: Use the shipped guarded registry update at Git-lock acquisition and final release, preserving the five-minute write limit and unrelated leases. Exercise activity timestamps and idle collection through the managed worktree service.

(cherry picked from commit f5d35bc)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit ba06dc3157f85e1a8f359c96d784c2050123a1ff)
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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: M 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