Skip to content

improve: reduce background allocation while waiting for directories - #200564

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-owned-directory-observation-alloc-20260919
Nov 17, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-owned-directory-observation-alloc-20260919

Conversation

@steipete

@steipete steipete commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Background Git and skill watchers rebuild absolute paths for every unrelated sibling event while waiting for a missing directory. This creates avoidable CPU and allocation pressure even when none of their watched content changes. The direct-root optimization in #181760 already handles existing roots; this change addresses the remaining ancestor fallback.

User Impact

Lower background allocation and CPU use while watched directories are absent. Directory creation/replacement, native-watch recovery, and recursive subtree filtering retain their existing behavior. No configuration, schema, or dependency change.

Why This Change Was Made

The observation owner already selects a nonrecursive ancestor watch when a directory is missing. Prepare the next child name at attachment and compare native child names directly, preserving Windows case folding. Keep containment checks for recursive subtree routing. Workspace Git discovery subscribes to missing .git directories at every ancestor; planned skill roots and Git reftable watches also use this path.

Production delta is +9 lines for the prepared attachment fact and platform comparison. No new cache or scan. The existing benchmark now supports the subprocess-era owner through a synthetic native adapter and can retain the missing subscriber during measurement.

Evidence

Five serial A1/A2/B samples, alternating order, on Node v26.12.1. The acceptance rule required B to beat both control medians for allocation, unprofiled CPU, and owner delivery time, with no >20% regression in comparable latency metrics.

Median metric A1 A2 B
Owner allocation MB/s 0.4462 0.4338 0.0209
Total allocation MB/s 0.4481 0.4342 0.0209
Owner bytes/event 12,019 11,692 564
CPU ms / 260,000 events 1,867.9 1,864.8 46.4
Owner delivery ms / 260,000 events 1,680.3 1,687.1 13.2
Owner batch p95 ms 0.4421 0.4428 0.0057

Owner allocation fell at least 95.2%, CPU 97.5%, and owner delivery time 99.2%. Allocation ranges were A1 0.416–0.464, A2 0.418–0.457, B 0.014–0.030 MB/s. CPU ranges were A1 1,855–1,918, A2 1,841–2,376, B 42–69 ms. Paced event-loop p99 medians were 10.92 / 7.45 / 8.68 ms: B is 16.6% above A2 and below A1, within the recorded threshold, with overlapping ranges on a busy host. This is source-owner evidence, not a full-Gateway latency claim.

Allocation sampling includes collected objects: 17 batches of 65 events, 1,750 ms between batches (~37 events/s). CPU samples separately use 4,000 batches without pacing. The synthetic APFS fixture contains 62,000 files totaling 1.14 GB, 5,000 session artifacts, and a sparse 35 GiB size-only placeholder. The observer does not read these contents; this does not measure database I/O or btrfs performance. One A2 sample crossed the benchmark's hourly recovery boundary and was rejected by the exact-notification assertion; it was repeated outside that diagnosed boundary without changing code or thresholds.

Reproduction:

# Save the baseline owner beside the current module, then use --owner for both A arms.
git show c8d5cf52b417a:src/infra/owned-directory-observation.ts > src/infra/owned-directory-observation.baseline.ts
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/owned-directory-events-measure.ts \
  --state-dir /path/to/new-result --watch-dir /path/to/synthetic-root \
  --missing --event rename --operations 17 --batch-delay-ms 1750 --allocations \
  --owner /path/to/owned-directory-observation.baseline.ts --output /path/to/result.json
# B omits --owner. CPU uses --operations 4000 --batch-delay-ms 0 and omits --allocations.

The extended ancestor regression is red on the baseline: 2,000 unrelated sibling events cause 12,000 path.resolve calls. Candidate makes zero and preserves creation/replacement assertions. All 11 owner tests and 76 consumer tests passed across workspace Git, branch caching, skills refresh, agent registry, and auth file state. The real-host missing-root/replacement test passed. One sibling native-host transport test timed out at 120 seconds in the initial combined run; its focused replay passed. That timeout is unclassified, not a claimed flake fix or inherited-CI waiver.

pnpm check:changed found a separate main regression: unused validateArtifactMetadata export in scripts/lib/actions-artifact-archive.mjs. The exact parent c8d5cf5 reproduces that finding with Knip 6.40.0 and the repository script-export configuration. Commit 7b0beee (#199838) deleted its last external consumer in full-release-receipt-recovery.mjs. Typechecks, changed-file formatting and lint pass; no exception or ignore was added.

Independent Codex autoreview of the final local change against c8d5cf5, P0–P2, completed scoped-clean with no findings. The committed patch is the reviewed implementation. No Control UI import of the changed owner was found.

Exact-head CI and final review

CI 44071220367 attempt 1 completed with one failed test shard: checks-node-changed-2, in gateway-transcripts-discord-capture.e2e.test.ts / “fences late Discord STT through the model-selected plugin instance”. The TCP-only socket fence at line 140 rejects native broker IPC as unexpected socket destination null:NaN; cleanup errors derive from that rejection. A clean checkout of exact parent c8d5cf52b417a reproduces the same failure with node scripts/run-vitest.mjs test/e2e/gateway-transcripts-discord-capture.e2e.test.ts --maxWorkers=1.

The causal change is 907e17b9ff49 / #200320: model-catalog preparation now calls createPluginCaptureOwner (src/agents/prepared-model-catalog-worker.pool.ts:75), which opens native IPC (src/process/spawn-broker/resource-client.ts:120). The test only admits loopback TCP to its provider and Gateway ports. Those owners and the test are unchanged between the exact parent, CI baseline 5fb231527f4f, and tested merge 47dda3f2e66c; this PR changes none of them. All other CI jobs passed or skipped, including security-fast. This is an attributed main regression, not a green CI claim.

ClawSweeper final review reviewed exact head 0c25e1e056604 with zero findings and zero open checklist items. Its optional request to establish the CI failure cause is answered above. Landing uses the explicitly authorized, pinned-head inherited-failure route with retained reproduction, source and checkout evidence.

Avoid repeated path resolution for unrelated sibling events while waiting for an absent watched directory. Retain recursive containment and native-watch recovery. Extend the existing callback benchmark and ancestor regression coverage.
@clawsweeper

clawsweeper Bot commented Nov 17, 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 scripts Repository scripts size: S labels Nov 17, 2026
@steipete
steipete marked this pull request as ready for review November 17, 2026 11:08
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T11:10:16.647480Z 0c25e1e Draft marked ready
ℹ️ 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 👀 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. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prepares the expected child name once when watching an ancestor of a missing directory, avoiding repeated path resolution for unrelated events.

Example: A watcher awaits /srv/openclaw/agents/work while state.sqlite-journal changes beside the missing agents directory.

  • Before: Each unrelated event resolves absolute paths before being ignored.
  • After: The watcher rejects the sibling name directly and still responds when agents is created.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and source-supported; performance evidence exercises an in-process adapter, and exact-head CI remains unresolved.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization supplies scoped callback-replay measurements and reports real-helper creation/replacement coverage, without claiming whole-Gateway performance improvement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Missing watched directories cause background Git and skills observations to spend CPU and allocate temporary paths for unrelated sibling activity.
Reason: The maintainer-authored direction has substantial measured owner-level savings and preserves the existing owner, lifecycle, and product configuration.

Merge readiness

✅ Ready for maintainer review

Keep open: this is a useful, focused performance improvement that current main does not provide; no introduced correctness or security defect was found.

Priority: P2
Reviewed head: 0c25e1e0566048bc8371bd8215e5efcf314e3beb

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared directory observer receives native events through the directory-watch helper and delivers scoped invalidations to Git, skills, config, and other filesystem-fact consumers.

flowchart LR
  A[Filesystem events] --> B[Directory watch helper]
  B --> C[Shared observation owner]
  C --> D[Prepared ancestor child filter]
  C --> E[Recursive containment filter]
  D --> F[Consumer invalidations]
  E --> F
Loading

Technical review

Best possible solution:

Retain the prepared attachment fact in the existing observer and preserve its recursive filtering and recovery contracts.

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

The base callback visibly resolves paths for unrelated ancestor events, and the supplied regression reports 12,000 path.resolve calls before the change versus zero afterward; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete approach: prepare the next child at attachment, compare names on nonrecursive ancestor events, and retain containment checks where recursive paths require them.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Directory-event filtering keeps the original intent (9dfbbc9: Avoid deriving paths when direct-root subscribers only need filenames, while retaining subtree filtering and rename recovery.)
  • Asynchronous attachment and recovery keeps the original intent (36afa92: Keep synchronous filesystem traversal and native-watch admission off the Gateway thread while preserving missing-root recovery.)
  • Benchmark adaptation keeps the original intent (189ed6f: Measure observer delivery through real subscriptions and deterministic callback replay, separately from filesystem throughput and helper transport.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 36afa92 adds src/infra/owned-directory-observation.ts:1 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 36afa92b2370; files: src/infra/owned-directory-observation.ts)

PR surface

Source +9, Tests +6, Docs +5, Other +52. Total +72 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 14 5 +9
Tests 1 7 1 +6
Docs 1 10 5 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 58 6 +52
Total 4 89 17 +72

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-test growth Runtime production +14/-5; tests +7/-1 The small runtime increase carries one attachment-derived fact; the existing regression gains a distinct ancestor-event work-count assertion.
Benchmark controls 3 new benchmark flags --missing, --watch-dir, and --batch-delay-ms control reproducible measurements without adding Gateway configuration.

Labels

Label changes:

  • add P2: Avoidable background CPU and allocation have measured owner-level impact, without evidence of an urgent availability regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Avoidable background CPU and allocation have measured owner-level impact, without evidence of an urgent availability regression.
  • 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.

Rank-up moves

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

  • Establish the cause of the socket-destination CI failure before treating the required gate as satisfied.

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.

Reviewed November 17, 2026, 6:24 AM ET / 11:24 UTC.

@steipete
steipete merged commit 6a9cffa into main Nov 17, 2026
219 of 224 checks passed
@steipete
steipete deleted the steipete/perf-micro-owned-directory-observation-alloc-20260919 branch November 17, 2026 11:41
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
Avoid repeated path resolution for unrelated sibling events while waiting for an absent watched directory. Retain recursive containment and native-watch recovery. Extend the existing callback benchmark and ancestor regression coverage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S 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