Skip to content

improve(agents): speed up subagent capability lookups - #152263

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-subagent-capability-lookup-20260918
Sep 19, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-subagent-capability-lookup-20260918

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated subagent capability and tool-policy checks rebuild the entire agent session store to find one session and its ancestors, adding avoidable work as session history grows.

User Impact

Capability and tool-policy resolution reads the requested session and its ancestry without materializing thousands of unrelated entries. Whitespace-padded legacy session IDs retain their depth, leaf restrictions, and inherited tool policy.

No schema change; index deferred. This change adds no index, migration, configuration, or operator action. A legacy ID miss can still scan the current-ID column for that one normalized ID; ordinary exact-key and exact-ID hits do not scan. Database formats, upgrade behavior, and writes are unchanged.

Why This Change Was Made

The session accessor owns current-ID selection and validation. Lookups try the exact session key, then the existing indexed current ID. Only if no visible exact-ID match exists does a SQLite trimmed comparison recover a padded legacy ID. Its whitespace set matches JavaScript String.trim(), including tabs, newlines, and Unicode whitespace. Exact IDs take precedence over padded duplicates; matches within each query retain session-key listing order. The reader excludes hidden entries and retained transcript generations and validates selected rows.

A lazy capability-store adapter memoizes keyed reads and misses within each synchronous resolution, then follows the existing cycle-checked parent chain. Explicit in-memory records retain their comparison semantics. The whole-store materializer is removed. The synchronous tools.effective request reuses its already-read exact-key entry; callers crossing asynchronous waits keep fresh reads.

Evidence

  • The new regressions failed before the compatibility repair: padded stored IDs lost their persisted depth. They now cover spaces, tabs/newlines, Unicode whitespace, inherited tool policy, and depth-2 leaf restrictions (canSpawn=false).
  • Spies verify capability resolution never calls the full-listing API and trimmed SQL runs only after an exact-ID miss. SQLite EXPLAIN QUERY PLAN verifies the exact-ID query uses the existing current-ID index.
  • Coverage includes memoized misses, fresh subsequent resolutions, exact-key prepared entries, cycles, cross-agent/fixed stores, hidden entries, duplicate IDs, retained generations, corruption refusal, and missing-store noncreation.
  • Earlier local synthetic comparison, 4,428 rows and 500 warmed capability lookups: 1.344 s before, 0.162 s after (8.3x faster). Peak process RSS, including setup/imports, was 520,126,464 bytes before and 459,472,896 bytes after. This is synthetic evidence, not a live deployment measurement.
  • 313 focused tests passed across 14 files. A final pass of all 71 affected reader, capability, and Gateway tests also passed.
  • node scripts/check-changed.mjs passed, including oxfmt, production/core-test tsgo, lint, dead-export, storage, and import-cycle checks. git diff --check passed.
  • Independent Codex autoreview completed with no actionable findings across P0–P3.

No live Gateway or full release validation was run. No deployment was performed.

Replace whole-store capability reads with per-resolution keyed reads and reuse synchronous prepared session entries. Preserve legacy whitespace-padded IDs with a trimmed query only after an exact current-ID miss. No schema change; a normalized-ID index is deferred.
@clawsweeper

clawsweeper Bot commented Sep 18, 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 agents Agent runtime and tooling labels Sep 18, 2026
@steipete
steipete marked this pull request as ready for review September 18, 2026 23:48
@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Sep 18, 2026
@clawsweeper clawsweeper Bot added 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. labels Sep 18, 2026
@clawsweeper

clawsweeper Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 18, 2026, 7:56 PM ET / 23:56 UTC.

ClawSweeper review

What this changes

Replace whole-store subagent capability reads with memoized session and ancestor lookups, preserve whitespace-padded legacy IDs, and reuse session metadata already read by the Gateway.

Merge readiness

⛔ Blocked before merge - 1 item remains

This optimization remains useful: current main still materializes the session store for capability lookups. No actionable introduced correctness or security defect was found.

Priority: P2
Reviewed head: 34596beba98aa4a0ae31d1c45a81da0ff1e6a47d

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with meaningful compatibility coverage and reported measurements; source review found no blocking defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository context identifies this as maintainer-authored internal work, so the external-contributor proof gate does not apply. The capability-reader benchmark and SQLite/Gateway regressions are relevant supplemental evidence; no live Gateway result is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository context identifies this as maintainer-authored internal work, so the external-contributor proof gate does not apply. The capability-reader benchmark and SQLite/Gateway regressions are relevant supplemental evidence; no live Gateway result is claimed.
Evidence reviewed 8 items Current main still needs the optimization: The fetched main implementation constructs a complete record from listSessionEntriesReadOnly before resolving individual sessions and their ancestry.
Bounded lookup lifetime: The new adapter memoizes entries and misses within each created lookup, excludes internal-effects keys, and delegates persisted reads to the session accessor. Prepared metadata is accepted only for the matching requested session key.
Storage and compatibility boundary: The accessor queries existing current-session IDs first, uses the documented trimmed fallback only after a visible exact miss, and validates selected rows through the existing reader. No schema, index, migration, write operation, or dependency change is introduced.
Findings None None.
Security None None.

How this fits together

Subagent capability resolution combines persisted session lineage with configured depth limits and inherited tool restrictions. Its results determine delegation permissions and the tool inventory shown by the Gateway.

flowchart TD
  A[Session key and configuration] --> B[Capability resolution]
  C[Gateway session metadata] --> B
  B --> D[Per-resolution lookup cache]
  D --> E[SQLite session reader]
  E --> F[Session and ancestor metadata]
  F --> B
  B --> G[Depth limits and tool restrictions]
  G --> H[Delegation and tool inventory]
Loading

Before merge

  • Resolve merge risk (P1) - The reported speedup is synthetic; its effect on live Gateway latency and memory use has not been measured.
Agent review details

Security

None.

PR surface

Source +163, Tests +397. Total +560 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 11 244 81 +163
Tests 3 397 0 +397
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 641 81 +560

Review metrics

Metric Value Why it matters
Production versus test growth Production +163 net lines; tests +397 net lines Production growth supplies keyed lookup and legacy-ID handling; regression coverage checks selection, restrictions, and cache lifetime.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep session selection and validation in the existing accessor, with resolution-local memoization preserving lineage and inherited restrictions.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep session selection and validation in the existing accessor, with resolution-local memoization preserving lineage and inherited restrictions.

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

Not applicable as a functional bug reproduction: this is a performance optimization, and current-main source confirms the whole-store materialization it targets.

Is this the best way to solve the issue?

Yes. Keyed reads through the existing session owner remove unnecessary materialization without adding persistent state or another policy implementation.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded performance improvement for repeated capability checks as session history grows.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository context identifies this as maintainer-authored internal work, so the external-contributor proof gate does not apply. The capability-reader benchmark and SQLite/Gateway regressions are relevant supplemental evidence; no live Gateway result is claimed.

Label justifications:

  • P2: This is a bounded performance improvement for repeated capability checks as session history grows.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository context identifies this as maintainer-authored internal work, so the external-contributor proof gate does not apply. The capability-reader benchmark and SQLite/Gateway regressions are relevant supplemental evidence; no live Gateway result is claimed.

Evidence

What I checked:

  • Current main still needs the optimization: The fetched main implementation constructs a complete record from listSessionEntriesReadOnly before resolving individual sessions and their ancestry. (src/agents/subagents/spawn/subagent-depth.ts:19, e623bcd437da)
  • Bounded lookup lifetime: The new adapter memoizes entries and misses within each created lookup, excludes internal-effects keys, and delegates persisted reads to the session accessor. Prepared metadata is accepted only for the matching requested session key. (src/agents/subagents/spawn/subagent-session-store.ts:67, 34596beba98a)
  • Storage and compatibility boundary: The accessor queries existing current-session IDs first, uses the documented trimmed fallback only after a visible exact miss, and validates selected rows through the existing reader. No schema, index, migration, write operation, or dependency change is introduced. (src/config/sessions/session-accessor.sqlite-exact-read.ts:132, 34596beba98a)
  • Prepared policy remains owner-derived: tools.effective passes its already-read canonical session entry directly into synchronous capability preparation. The added handler regression exercises inherited MCP denial through the real final-policy filter. The patch does not expose prepared metadata as client input or change execution authorization. (src/gateway/server-methods/tools-effective.ts:627, 34596beba98a)
  • Regression coverage and reported measurements: Inspected tests cover per-resolution freshness, prepared-key mismatch, partial records, lineage cycles, padded IDs, hidden entries, retained generations, corruption refusal, and missing-store noncreation. The captured PR body reports 500 warmed lookups over 4,428 rows improving from 1.344 seconds to 0.162 seconds, with peak RSS decreasing from 520,126,464 to 459,472,896 bytes; it explicitly identifies these measurements as synthetic and reports no live Gateway run. Reported test passes were not independently executed. (src/agents/subagents/spawn/subagent-capabilities.store.test.ts:32, 34596beba98a)
  • Existing capability contract: Documentation makes current depth policy authoritative while retaining spawn-time sender restrictions for senderless child resumes. The optimization retains these policy owners and changes their metadata acquisition. Public docs: docs/tools/subagents/nesting.md. (docs/tools/subagents/nesting.md:69, 34596beba98a)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

@steipete
steipete merged commit 16b1fb7 into main Sep 19, 2026
281 checks passed
@steipete
steipete deleted the steipete/perf-subagent-capability-lookup-20260918 branch September 19, 2026 00:16
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 19, 2026
* commit 'ca69b4d25dfcd488acc6ba1d878e4b4252f40cd2': (325 commits)
  perf(gateway): streamline config reload comparison (#152279)
  fix(xai): reject invalid UTF-8 OAuth responses (#111737)
  fix(release): accept waived advisory performance evidence for stable publication (#152290)
  fix: deliver watcher results while other sessions are busy (#152287)
  perf(media): reuse attachment filename classification (#152274)
  refactor(build): reuse forwarded option scanning (#152293)
  chore(diagnostics-otel): revert unapproved duration-bucket merge (#152292)
  fix: stop chat media reads after access changes (#152219)
  fix(test): use Gateway WebSocket transport in network fixtures (#152143)
  improve: retain quota refresh evidence from successful CI runs (#152173)
  improve(gateway): reduce memory used by session selection (#152260)
  perf(agents): use keyed subagent capability lookups (#152263)
  refactor(matrix): centralize media metadata assembly (#149128)
  chore(ui): refresh control ui locales (#152276)
  feat: open Crabbox apps beside the conversation (#152094)
  refactor: simplify worker and model fallback handling (#152268)
  perf(codex): reconcile session catalogs incrementally (#152257)
  fix(ui): keep submitted prompts visible across session startup (#152241)
  perf(sessions): move automatic maintenance database work to workers (#148630)
  fix: preserve reply metadata through outbound preparation (#152231)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 19, 2026
Replace whole-store capability reads with per-resolution keyed reads and reuse synchronous prepared session entries. Preserve legacy whitespace-padded IDs with a trimmed query only after an exact current-ID miss. No schema change; a normalized-ID index is deferred.
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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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