Skip to content

perf(state): skip identity refreshes for content-only events - #183348

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-owned-dir-observation-20260919
Oct 25, 2026
Merged

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

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Concurrent agent turns repeatedly stat unchanged agent database identities when SQLite emits ordinary content-change notifications.

User Impact

Reduces filesystem work during busy Gateway sessions when native watchers report named change events, while retaining database replacement/deletion detection and existing write-admission checks. No configuration or migration is needed.

Why This Change Was Made

The shared directory observer discarded the native event type. Identity/presence consumers therefore treated named content writes like possible file replacement. Forward that existing event fact and let the three identity owners skip named change notifications. Rename/unlink, nameless events, watcher recovery, and the existing periodic reconciliation still refresh identities.

The observers already watch state directories and necessary ancestors, and their owners already coalesce refreshes. Content-sensitive consumers still need every notification, so filtering stays with the identity owners. This adds no cache, timer, or second invalidation owner. Runtime code grows by 11 lines to preserve and consume the event classification; no existing lifecycle mechanism becomes redundant. The non-test delta is +407 lines: +11 runtime and +396 benchmark tooling. The larger tooling change supplies the required fixed-duration workload, verified real tool results, synchronized starts, main-isolate profiling, and filesystem counters in the existing benchmark CLI. Tests add 86 net lines.

Evidence

Two concurrent, counterbalanced Linux pairs used Node 26.12.1 and the built base/candidate artifacts. Each side had 16 interleaved virtual CPUs and an isolated native Linux filesystem; each admission window lasted 600 seconds plus drain. The measured base was fdad53b1bc1d66d98a11da12fb633a75f8285ecb; the runtime patch remained byte-for-byte identical after rebasing onto current main.

The small, consistent result is fewer filesystem calls: database stats/turn fell 1.14%, and all measured stat calls/turn fell 1.39%. This does not establish a whole-Gateway CPU speedup. A separate 600-second main-isolate allocation pair was essentially flat: 159.43→159.23 MiB/s (−0.12%), or 168.52→167.15 MB per verified turn (−0.81%). This single sampled pair is context, not a claim of a broad allocation improvement.

Paired timing, work counts, and memory
Metric Base Candidate Absolute change Relative change
Main CPU (%) 79.207 79.578 +0.371 +0.47%
Main CPU (ms/turn) 547.215 554.718 +7.503 +1.36%
GC (s/min) 3.874 3.800 -0.074 -1.92%
GC (ms/turn) 44.693 44.346 -0.347 -1.04%
Loop p99 (ms) 216.334 217.907 +1.573 +0.60%
List p99 (ms) 920.604 788.644 -131.960 -11.97%
List p95 (ms) 367.730 363.217 -4.513 -1.19%
Peak RSS (MiB) 3654.072 3649.848 -4.225 -0.00%
Final heap (MiB) 564.301 564.022 -0.279 -0.16%
DB stats (/s) 882.484 866.387 -16.097 -1.90%
DB stats (/turn) 609.662 602.696 -6.966 -1.14%
Watch deliveries (/s) 141.317 146.097 +4.779 +3.20%
All stat calls (/turn) 753.268 742.820 -10.449 -1.39%
Pair linux/pair-1/base / linux/pair-1/candidate: turns 885/852; loop n=19086/18859; list n=1228/1236; GC max 368.520/281.726 ms; major n=57/59
Pair linux/pair-2/base / linux/pair-2/candidate: turns 949/975; loop n=19127/19378; list n=1214/1223; GC max 612.642/281.313 ms; major n=65/67

Relative changes are the mean of per-pair relative changes; absolute changes are the mean paired differences. CPU/turn and GC/turn normalize the whole mixed workload, including fixed-rate probes. Final RSS rose 1.03%; final heap and sampled peak RSS were roughly neutral. Observed heap growth differed (+53.91 MiB mean); these unforced snapshots can reflect GC phase and do not establish a retention improvement. Exact loop p95 was not collected.

All 885/852 and 949/975 admitted turns were verified, with matching provider/tool accounting and successful recorded probes. Start skews were 59.331 and 26.364 ms. No diagnostic samples were dropped. Each run also recorded one worker-reservation error aggregate without its cause; no failed turn or probe was visible, but the aggregate does not establish why that operation failed.

Total GC p95 was 29.182→31.870 ms (n=4527/4462) and 20.734→20.606 ms (n=4806/4911); total GC p99 was 88.574→87.038 and 76.798→73.726 ms with the same counts. Major-GC and incremental-GC percentile samples were too few for tail conclusions. No untraced decision metric crossed the predeclared rejection thresholds; no additional control run was required by those results.

Allocation scope and residual cost

The main-only capture included collected objects at a 32 KiB sampling interval, ran for 614.906/614.658 seconds, verified 610/614 turns, and had clean exits and no collector loss. The targeted stats subtree below owned-directory callbacks recorded 3,353,976 sampled bytes on base and none on candidate; zero sampled bytes is not proof of zero allocation. The broader observer subtree increased from 398.89 to 437.72 MB (0.619→0.679 MiB/s), chiefly path resolution under isPathInside. Native deliveries also increased from 96.63 to 101.38/s. This fixture did not reproduce the original production allocation family's size, and this PR does not claim that broader cost was removed.

The initial allocation attempt failed before any measured load because worker profiling could not resolve a source-module import under native Node. The new fixed-duration mode now explicitly captures the requested main isolate and omits worker-manifest metadata. A paired real-Gateway heap smoke passed before the full capture was repeated; no runtime code or untraced workload changed for that repair.

Platform and fixture limits

Native macOS probes reported content writes as rename, so this optimization does not activate for that event stream. Four earlier sequential Mac windows on a busy shared host had essentially flat database stats/turn (+0.20%), CPU/turn +13.14%, GC/min +23.33%, loop p99 +58.20 ms, and list p99 +0.11 ms on the paired absolute mean. Those uncontrolled timings remain inconclusive and are not evidence of a Mac performance improvement. Linux native events in the measured workload were over 99.96% named content changes.

History probes hit their bounded 2,050-sample budget roughly halfway through each window; list/search/subscription churn continued throughout. The fixture uses one agent database and short tool-result markers, so it does not quantify benefits from a larger database catalog or production-sized tool payloads. The Mac and Linux evidence are not combined into one performance estimate.

The built local Gateway workload uses synthetic state only: 10,000 sessions (mostly archived subagent inventory), 40 plugins, 36 concurrent mock-provider turns executing read/grep tools in managed worktrees, and 64 WebSocket clients with list/search/sidebar/history churn. Each admission window lasts 600 seconds, followed by draining. Timing/GC runs are untraced; sampled allocation is measured separately. Filesystem counters cover the main thread and native watcher-host deliveries, not worker-thread stat calls. This fixture uses one agent database, does not seed persisted dashboard boards, and returns short tool-result markers after reading/grepping the fixture files. Allocation rates use the profiler capture duration.

  • Four directly affected test files: 90 passed. Source-discovery and validation regressions fail on the base at the expected unnecessary-stat assertion and pass with the fix. Replacement/deletion, nameless notifications, and recovery remain covered.
  • Harness/CLI tests: 60 passed, 7 platform skips. Built-Gateway paired release and interrupted-barrier smokes passed, including verified read/grep turns and clean Gateway shutdown.
  • Export-name collision guard passed; eager-import and PR-wrapper source closure guards: 22 passed.
  • Changed-file formatting and lint passed; git diff --check passed.
  • Independent subagent review (autoreview route unavailable): clean after fixing harness setup/shutdown and cancellation findings. The configured review helper refused its provider-route mismatch before inference; no operator configuration was changed.

@clawsweeper

clawsweeper Bot commented Oct 25, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 06:34
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T06:36:45.335955Z c606f04 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.

@github-actions

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: c606f04c3018646a53c693e8308f973a71954b69
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/file-state.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The PR forwards filesystem event types so three identity owners can skip content-only notifications, and extends the existing benchmark to measure sustained workloads.

Example: Linux reports a named change event for openclaw-agent.sqlite during an agent turn.

  • Before: Identity consumers perform filesystem checks even though the file was only written.
  • After: Identity consumers skip that notification while replacement, deletion, recovery, and periodic reconciliation retain their checks.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The reported Gateway measurements support the narrow call-count claim, and source review found no actionable defect; broader speedup claims are appropriately excluded.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; its body reports built local Gateway CLI workloads on isolated Linux filesystems, verified mock-provider tool turns, fewer identity-related stat calls, and preserved replacement/deletion regression coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Busy Gateway sessions perform avoidable filesystem work when ordinary SQLite writes trigger identity refreshes.
Reason: The area owner's direction is established by maintainer authorship, and the modest measured benefit costs little runtime complexity; the larger benchmark extension makes the workload reusable.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR makes a measured, narrowly scoped optimization, and review found no actionable introduced defect.

Priority: P2
Reviewed head: c606f04c3018646a53c693e8308f973a71954b69

Before merge

None.

Findings

None.

Agent review details

How this fits together

Native directory notifications enter the shared observer, which delivers invalidations to auth-file, session-source, database-validation, and other consumers; each consumer owns its retained facts.

flowchart TD
  A[Native directory events] --> B[Shared directory observer]
  B --> C[Auth file identity owner]
  B --> D[Session source owner]
  B --> E[Database validation owner]
  B --> F[Content sensitive consumers]
  C --> G[Existing admission and effect checks]
  E --> G
Loading

Technical review

Best possible solution:

Retain the small owner-local event filter and existing invalidation safeguards, with the benchmark supporting only the measured filesystem-work reduction.

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

Source inspection shows named content events reaching identity stat checks on current main; the PR reports matching base-failing regressions and built-Gateway measurements, which were not rerun during this read-only review.

Is this the best way to solve the issue?

The change uses the smallest existing runtime boundary: preserve event classification in the observer and let identity owners skip irrelevant work while content-sensitive consumers continue receiving notifications.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared directory observation and database validation keeps the original intent (3ac0c05: Retain process-owned filesystem facts with external invalidation and coarse recovery while preserving physical admission checks.)
  • Auth-profile file identity keeps the original intent (3ccacf7: Keep auth facts in their existing owner, publish native writes immediately, and retire replaced sources without repeated hot-path probes.)
  • Session-source observation lifecycle keeps the original intent (refactor(gateway): refresh session discovery watches in place #176786: Refresh the bounded source memo in place and retain common watches while receivers continue validating physical candidates and disclosure authority.)
  • Benchmark tool and request evidence keeps the original intent (3938a12: Count actual workload phases and require successful tool execution plus the expected visible reply rather than trusting aggregate request totals.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3ac0c05 adds src/state/openclaw-agent-db-validation-cache.ts:92 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3ac0c058fe16; files: src/state/openclaw-agent-db-validation-cache.ts)

PR surface

Source +11, Tests +86, Other +396. Total +493 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 19 8 +11
Tests 5 99 13 +86
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 454 58 +396
Total 11 572 79 +493

Review metrics

Metric Value Why it matters
Runtime, tooling, and test growth Runtime net +11 LOC; benchmark tooling net +396 LOC; tests net +86 LOC. Runtime growth carries existing event facts through existing owners; tooling growth provides sustained measurement, synchronized starts, verified tool results, and filesystem counters.
Benchmark controls One new flag: --start-barrier; existing --duration-ms also supports normal mock workloads. These controls affect explicit benchmark invocations and introduce no product configuration or persisted preference.

Labels

Label changes:

  • add P2: This is a limited performance improvement for busy Gateways whose watchers emit named content-change events.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: This is a limited performance improvement for busy Gateways whose watchers emit named content-change events.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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.

Reviewed October 25, 2026, 2:51 AM ET / 06:51 UTC.

@steipete
steipete merged commit 99dd80d into main Oct 25, 2026
228 of 231 checks passed
@steipete
steipete deleted the steipete/perf-micro-owned-dir-observation-20260919 branch October 25, 2026 06:59
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts security-sensitive-changed 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