Skip to content

perf(gateway): reduce operator authority check allocations - #179165

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-buf-authority-recheck-20261021
Oct 21, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-buf-authority-recheck-20261021

Conversation

@steipete

@steipete steipete commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Operator turns with access-policy plugins repeatedly allocate principal serialization, profile copies, and assertion closures while checking authority.

User Impact

Authority checks allocate less without delaying revocation or changing access decisions. Every live plugin, grant, role, config, and contextual-ingress check remains in place. No configuration or migration is required.

Why This Change Was Made

The auth-policy owner recognizes immutable policies it already issued for the same config; contextual-ingress policies remain uncached. Retained access grants avoid preparing a plugin profile unless a policy callback needs one. Composed source traversals and bound model checks reuse their functions rather than rebuilding them on every assertion. This reuses facts and functions, never a plugin's answer.

The apparent repeated checks around plugin/host callbacks are retained: callbacks can synchronously revoke the original authority. The generic plugin invocation/async context machinery is outside this change.

Evidence

Five real source-Gateway turns on baseline ed8e68c9d15d1259b8d1155a4078f6759bb01e9b and the final candidate produced identical live plugin-assertion counts: [1662, 1642, 1642, 1642, 1642]. Median: 1,642/turn, 547.33/tool completion, 328.4/committed message append. Each turn completed three tools and five message appends (six raw transcript updates). Admission/warmup is outside capture; the retained policy's authorize/resume callbacks remain zero in the turn window on both versions. These grouped runs establish count equivalence, not a timing comparison.

Five concurrent pairs per scenario (25 pairs total, 50 processes), Node v26.8.2 on Linux x86-64. Each process performs 100,000 checks after 20,000 warmups, with HeapProfiler sampling at 32 KiB including collected objects. Baseline is ed8e68c9d15d1259b8d1155a4078f6759bb01e9b; candidate is that source plus the final runtime changes. The same benchmark harness runs on both sides; the four changed runtime files are identical in the rebased PR head. Both sides share a start deadline under the exclusive measurement lock; A/B CPU halves 96–111 and 112–127 swap each pair.

Owner probe Baseline bytes/check, median (p95) Candidate bytes/check, median (p95) Median paired change
Auth-policy recapture 2,654 (2,697) 0 (0.33) -100.0%
Retained plugin grant 4,660 (4,717) 4,490 (4,512) -3.5%
Bound model execution 10,249 (10,343) 4,501 (4,533) -56.2%
Admitted-run guard 8,286 (8,324) 4,962 (5,011) -40.0%
Transcript guard 8,858 (8,935) 5,493 (5,531) -38.0%

Changes are the median of each pair’s (candidate − baseline) / baseline, not the ratio of column medians. Auth-policy recapture is below sampling resolution: candidate range 0–0.33 bytes/check, rather than a claim that every process allocates literally zero bytes.

The predeclared 60% allocation target was not met by the composed guards: bound model execution improves 56.2%, admission 40.0%, and transcript guards 38.0%. The bound-model result is a 2.28× reduction in median allocated bytes; its remaining allocation is close to the retained-plugin check itself. Generic plugin invocation/frame allocations are deliberately unchanged. Retained-grant timing is neutral (+0.6% paired median, range −9.2% to +6.4%); every other probe improves elapsed and main-thread CPU time.

All 50 processes rejected a revoked plugin grant on the next check outside capture. Each composed probe still performs one auth-policy check, one resume-owner check, and one live plugin assertion per invocation. No live check or plugin answer is memoized.

Timing, allocation spread, load, and reproduction

Times below include the allocation profiler and are owner-call measurements, not end-to-end turn latency. Values are median [minimum–maximum]; with five samples, nearest-rank p95 is the maximum.

Probe Elapsed µs/check, baseline → candidate Median paired elapsed change Main-thread CPU µs/check, baseline → candidate
Auth-policy recapture 1.006 [0.978–1.060] → 0.018 [0.017–0.023] -98.1% 0.999 [0.980–1.053] → 0.020 [0.020–0.020]
Retained plugin grant 3.294 [3.268–3.595] → 3.316 [3.036–3.486] +0.6% 3.283 [3.267–3.597] → 3.317 [3.037–3.486]
Bound model execution 7.394 [6.769–7.882] → 3.484 [3.418–3.755] -53.6% 7.376 [6.749–7.817] → 3.473 [3.416–3.757]
Admitted-run guard 5.250 [5.064–7.963] → 4.339 [3.931–6.909] -22.2% 5.242 [4.974–6.286] → 4.261 [3.875–4.658]
Transcript guard 5.635 [5.297–6.245] → 4.265 [4.028–4.659] -24.6% 5.531 [5.275–6.050] → 4.264 [4.020–4.331]
Probe Baseline bytes/check range Candidate bytes/check range
Auth-policy recapture 2,585–2,697 0–0.33
Retained plugin grant 4,611–4,717 4,443–4,512
Bound model execution 10,226–10,343 4,408–4,533
Admitted-run guard 8,206–8,324 4,948–5,011
Transcript guard 8,826–8,935 5,414–5,531

Recorded mpstat -P 96-127 context: mean observed CPU utilization (%) by pair, including benchmark CPU. All pairs are retained, including higher-load admission samples; load does not invalidate the concurrent comparison.

Probe Pairs 1–5 CPU utilization
Auth-policy recapture 16.89, 10.81, 8.07, 7.10, 13.20
Retained plugin grant 13.87, 9.03, 11.58, 8.86, 7.67
Bound model execution 14.48, 19.63, 11.91, 10.55, 12.67
Admitted-run guard 34.61, 31.43, 14.14, 13.12, 15.64
Transcript guard 18.03, 12.86, 17.55, 10.65, 12.62

Owner workload, invoked separately on each side with the same start timestamp:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/operator-authority-measure.ts \
  --scenario model-execution --iterations 100000 --warmup 20000 \
  --sampling-interval 32768 --start-at <shared-unix-ms> --output <result.json>

Repeat for all five scenario names in the script. The real-turn count recipe is in Operator authority allocations.

Focused validation: 126 tests passed across the five files below; after the final lazy-profile adjustment, the five original-grant recovery/revocation cases passed again. Changed-file oxfmt and lint, one pnpm tsgo:core (native tsrs), and git diff --check passed. Independent Codex review found no actionable P0–P2 findings, including a follow-up review of the final profile sharing. CI run 39558320084 passed on 9462cd879218321bd347e7e698aef50773aebae1; required openclaw/ci-gate checks are successful. A later rebase conflict only combined the benchmark launcher’s new optional memory preload with the auth-mode argument; runtime code is unchanged and the resolved script passed formatting/lint.

  • src/gateway/server/ws-origin-policy.test.ts
  • src/config/sessions/session-source-authority.test.ts
  • src/gateway/operator-run-recovery.test.ts
  • src/gateway/operator-role-policy.test.ts
  • src/agents/admitted-run-context.test.ts

Runtime production delta: +24 lines (+37/−13). This growth records same-config policy provenance without a cast and retains reusable traversal functions; eager serialization/copies/closures disappear from repeated checks. The requested non-test, non-docs/ diff is +617 net lines: +24 runtime, +517 benchmark tooling, +76 benchmark documentation. The larger diff is required to make the plugin-enabled owner and real-turn reproduction rerunnable; it adds no production capability or test-only runtime hook. Serialization is still required for fresh principals, serialized recovery policies and contextual ingress.

The tiny plugin-enabled fixture proves the non-owner/tool path, not deployment capacity. The full deployment-shaped Gateway A/B and overall GC effect remain the lead's pre-merge checks. This PR is intentionally left open.

Recheck trace and proof scope

tool-authority.runtime checks admitted authority directly and again through ordinary host capabilities. Reply checks add an explicit operator assertion; registration composes both (at least three operator checks, ordinarily five with host capabilities). Transcript rewrite composes outer/inner write admission and captured transcript guards. These are source-derived lower bounds, not per-turn measurements.

Recovery checks current identity/config before and after policy callbacks, and rechecks the original grant after other policy callbacks. Existing regression tests cover a callback revoking the original grant and role changes during source assertions. A repeated composition frame alone does not prove a duplicated leaf check.

The owner microbenchmark uses a real registered synthetic access-policy plugin and non-owner identity; it measures isolated owner calls, not storage or complete model turns. The opt-in Gateway driver separately counts real chat.send --stress-tools turns. Its per-tool/per-append figures normalize all assertions in the turn window and do not attribute assertions to individual effects.

@clawsweeper

clawsweeper Bot commented Oct 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T06:56:06.482145Z cede7db PR opened
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 21, 2026
@github-actions

github-actions Bot commented Oct 21, 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: 9462cd879218321bd347e7e698aef50773aebae1
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/auth-policy.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@steipete
steipete force-pushed the steipete/perf-buf-authority-recheck-20261021 branch from cede7db to 9462cd8 Compare October 21, 2026 06:53
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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: 🦐 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reduces repeated authority-check allocations and adds benchmarks for operator checks and Gateway turns.

Example: [email protected] completes a Gateway turn with three tools and five committed message appends.

  • Before: Repeated checks serialize an already-issued principal, prepare unused profile copies, and rebuild assertion functions.
  • After: The existing owners reuse immutable facts and functions while continuing live checks; reported median plugin assertions remain 1,642 per turn.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-reviewed without a discrete defect; supplied runs establish count equivalence rather than the claimed allocation benefit.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied source-Gateway turns exercise the non-owner plugin/tool path and show equivalent assertion counts, while performance acceptance results remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Plugin-enabled operator turns repeatedly create temporary objects while checking authority.
Reason: The area contributor has approved the direction through this maintainer-authored PR, and the runtime change is focused; acceptance of its performance benefit remains subject to the declared measurement.

Merge readiness

✅ Ready for maintainer review

Keep this maintainer-authored PR open as requested; the focused optimization preserves the reviewed authority contracts, with no actionable code finding.

Priority: P2
Reviewed head: 9462cd879218321bd347e7e698aef50773aebae1

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared paired allocation/CPU results and deployment-shaped Gateway A/B remain pending; the new contextual-ingress test protects an invariant rather than demonstrating an existing functional failure.
Agent review details

How this fits together

Gateway authentication and plugin grants feed admitted agent authority, which checks model execution, tools, and transcript writes.

flowchart TD
  A[Authenticated operator] --> B[Gateway auth policy]
  B --> C[Live plugin grant]
  C --> D[Admitted run authority]
  D --> E[Model and tool execution]
  D --> F[Transcript write guards]
Loading

Technical review

Best possible solution:

Keep these owner-local optimizations if the declared performance comparison demonstrates the allocation gain without a material runtime regression.

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

Current main visibly repeats principal serialization, eager profile preparation, and assertion construction; supplied Gateway counts establish execution frequency, but this read-only review ran no target code.

Is this the best way to solve the issue?

The smallest complete approach is to reuse immutable policy provenance and traversal functions at existing owners while preparing profiles only for callbacks; the diff follows that approach without caching live plugin answers.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Authentication policy capture keeps the original intent (32d3642: Separate transport-policy changes from revocation of an accepted principal's grant.)
  • Retained plugin access grants keeps the original intent (001d2a8: Reuse the original grant while checking other policies and asserting that grant after their callbacks.)
  • Composed session source assertions keeps the original intent (79e33e8: Preserve each source owner's preparation, scoped authority, and cleanup contracts.)
  • Bound model execution keeps the original intent (59863f5: Preserve authorization failure mapping and irreversible execution revocation.)
  • Benchmark instrumentation keeps the original intent (db44c87: Measure allocation alongside CPU, promotion, GC, and latency before accepting performance changes.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Shakker: Raw commit 65e49fa adds src/gateway/operator-access-policy.ts:244 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 65e49fa2008c; files: src/gateway/operator-access-policy.ts)

PR surface

Source +24, Tests +21, Docs +76, Other +517. Total +638 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 37 13 +24
Tests 1 21 0 +21
Docs 1 76 0 +76
Config 0 0 0 0
Generated 0 0 0 0
Other 3 532 15 +517
Total 9 666 28 +638

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +37/-13; tests +21/-0 The small runtime increase records config-scoped provenance and reusable traversals; the added test protects live contextual-ingress revocation.
Benchmark controls 8 benchmark CLI options; 0 production configuration additions Seven options configure the new owner probe, and one enables operator-policy instrumentation in the existing Gateway driver.

Labels

Label changes:

  • add P2: A focused allocation improvement for plugin-enabled operator turns, with no demonstrated urgent user-facing outage.
  • 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: A focused allocation improvement for plugin-enabled operator turns, with no demonstrated urgent user-facing outage.
  • 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.

  • Complete the predeclared paired allocation and CPU comparison and the deployment-shaped Gateway A/B.

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 21, 2026, 3:09 AM ET / 07:09 UTC.

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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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