Skip to content

perf(gateway): reduce repeated turn preparation work - #134673

Merged
steipete merged 2 commits into
mainfrom
codex/gateway-turn-preparation-cleanup
Sep 1, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/gateway-turn-preparation-cleanup

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway turns repeated plugin-policy preparation and copied session data that the turn only needed to identify its current session. These costs accumulated during model/tool discovery, browser chat admission, and transcript persistence.

Related: #134246, the earlier per-turn preparation improvement. This is the requested follow-up performance and simplification pass.

Why This Change Was Made

Reuse each scan's normalized plugin policy, read the global enabled flag directly where it is the only needed fact, and keep policy decisions in the existing eligibility owner. Remove forwarding helpers and repeated owner checks after the owner has already passed the outer gate.

Transcript targeting carries the current session ID without retaining or copying the cached store. Private identity snapshots retain freshly decoded entries; caller callbacks and returned results retain their isolation copies. Existing current-session checks, durable input admission, cancellation ordering, plugin deny/allow rules, installed-plugin activation, and named bundled compatibility remain intact. No config, persistence schema, migration, dependency, or protocol change.

User Impact

Less repeated local work during turn preparation with the same available tools and durable chat behavior. This does not claim a repeatable end-to-end latency improvement: provider latency, shared-host load, and garbage collection varied between runs.

Evidence

  • Earlier isolated real-API measurements reduced plugin normalization from 5,678 to 1,422 calls across two turns (75%), and session-entry copies from 508 to 476 across two turns (6.3%). All 32 redundant identity-snapshot copies disappeared. Timing and precise counting used separate runs.
  • The last measured plain preparation median was 115.25 → 97.93 ms, while Gateway CPU was effectively flat. These historical measurements were made on e339ce2e2fb3d9c4e1d42c9473a35479ccaffe9b plus the preceding local performance passes. They are not final-head timing claims; newer main changes full-store caching.
  • The three local passes validated 338, 160, and 86 real OpenAI turns respectively, covering plain responses, workspace file reads, session-status tools, and browser-protocol admission. Same saved state and full builds were used for comparisons. No task-owned test/build/review jobs overlapped timed runs.
  • The identity-copy regression failed before the fix in three cases: six async copies exceeded a budget of four, and two synchronous cases each made two copies against a budget of zero. Existing tests retain stale-write, recovery, checkpoint, provenance, and cancellation-ordering proof. Final cleanup adds direct callback/result isolation, shared prepared-policy immutability, and a positive-control owner-denial table row.
  • Runtime validation on faa28eb7040adaaf11c84496eb2b30063c206a66: 155 tests across nine files passed, covering policy selection, manifest eligibility, browser admission, exact session rows, conformance, recovery, transcript initialization, parent forks, and replacement projection. The full build and changed-file gate passed; Codex Autoreview found no actionable finding at its configured P0 threshold.
  • Fresh real-API smoke on that rebased build: six of six turns passed through the authenticated browser Gateway protocol. Two plain turns returned the exact expected text; two workspace reads completed their command tool and returned the fixture; two session-status turns completed session_status and returned the configured public model. Gateway health returned HTTP 200. This is behavior proof, not a new timing claim.
  • Earlier focused passes: 333, 352, and 84 tests passed; matching full builds and changed checks passed. Local final checks used the checkout’s existing resolved dependencies; hosted CI supplies the current frozen-lockfile environment. CI for the runtime-change commit passed: 190 jobs successful, 15 skipped, no failures. The final follow-up 858138db7e15547a29ab3cd7f1434f5f239c99be only removes the changelog line; source and tests match the validated commit byte-for-byte. Its focused Autoreview passed, and final-head CI is green.

Production LOC: net −59. Tests: net +117. The tests reuse existing owner fixtures and add no production-only test seam.

Follow-up: startup-only preserveTemporarySessionMapping has another fresh-row copy to investigate separately. A direct exact-reader substitution for Gateway whole-store lookup is intentionally excluded because hidden-row visibility, sparse-store shape, and unrelated-row validation differ.

ClawSweeper follow-through: its current review found the runtime patch correct. The changelog removal finding/rank-up move is addressed: the release-owned changelog is unchanged, and the release-note context remains in this PR body. The first native prepare attempt correctly rejected the changelog line; no release-only override was used. The exact-head CI rank-up move is satisfied by the green final-head run.

@clawsweeper

clawsweeper Bot commented Sep 1, 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 gateway Gateway runtime agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Sep 1, 2026
@steipete
steipete marked this pull request as ready for review September 1, 2026 02:37
@steipete
steipete requested a review from a team as a code owner September 1, 2026 02:37
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 31, 2026, 10:59 PM ET / September 1, 2026, 02:59 UTC.

ClawSweeper review

What this changes

This PR removes redundant plugin-policy normalization and session-entry copies from Gateway turn preparation while preserving tool eligibility and guarded transcript persistence.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

Keep open. The exact PR head has no actionable regression found, and the earlier release-owned changelog finding is resolved; this maintainer-authored, maintainer-labeled PR remains subject to normal exact-head merge gates.

Priority: P3
Reviewed head: 858138db7e15547a29ab3cd7f1434f5f239c99be

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A normal good-quality cleanup: source and focused regression coverage support the ownership-preserving refactor, with no actionable review finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The repository state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the PR body additionally documents an authenticated Gateway smoke over the changed preparation path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the PR body additionally documents an authenticated Gateway smoke over the changed preparation path.
Evidence reviewed 6 items Exact PR scope: The reviewed merge-base-to-head delta contains the 16 declared source/test paths; the final follow-up changes only CHANGELOG.md, so all runtime behavior remains identical to the previously reviewed runtime commit.
Plugin policy owner retained: Callers normalize once from the same config and pass that value into the existing manifest eligibility owner, which still applies disabled-entry, denylist, and restrictive-allowlist rules.
Transcript session fence retained: The recorder borrows the current entry only to match the admitted session ID, then supplies that ID as expectedSessionId; guarded transcript persistence re-reads and validates it before committing.
Findings None None.
Security None None.

How this fits together

Gateway turns prepare plugin metadata, model/tool availability, and session facts before dispatching work and writing transcript state. The changed paths reduce repeated preparation while the existing policy and SQLite transaction owners continue to decide availability and persistence.

flowchart LR
  A[Gateway chat turn] --> B[Prepare runtime facts]
  B --> C[Plugin policy eligibility]
  B --> D[Session identity lookup]
  C --> E[Tools and models]
  D --> F[Guarded transcript write]
  E --> G[Turn dispatch]
  F --> G
Loading

Before merge

  • Complete next step (P2) - No repair lane is needed: the prior changelog finding is fixed and this cycle found no discrete, automatable patch defect.
Agent review details

Security

None.

PR surface

Source -59, Tests +117. Total +58 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 12 52 111 -59
Tests 4 165 48 +117
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 217 159 +58

Review metrics

Metric Value Why it matters
Production versus test delta production −59 lines; tests +117 lines The cleanup reduces production surface while adding focused policy, session-isolation, and Gateway-admission regression coverage.

Technical review

Best possible solution:

Preserve this owner-boundary consolidation and land it only after the exact head satisfies the repository’s normal required checks.

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

Not applicable: this is a performance/simplification PR, not a report of broken existing behavior. The supplied PR body documents real after-fix Gateway turns, while source review confirms the preserved policy and persistence paths.

Is this the best way to solve the issue?

Yes. Reusing same-config normalized policy at the existing eligibility owner and retaining only the session binding avoids duplicate checks and redundant copies without creating a parallel policy or persistence path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 9aa82b18253b.

Labels

Label justifications:

  • P3: This is a contained preparation-performance cleanup with no evidence of an urgent user-facing regression.
  • 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 state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the PR body additionally documents an authenticated Gateway smoke over the changed preparation path.

Evidence

What I checked:

  • Exact PR scope: The reviewed merge-base-to-head delta contains the 16 declared source/test paths; the final follow-up changes only CHANGELOG.md, so all runtime behavior remains identical to the previously reviewed runtime commit. (858138db7e15)
  • Plugin policy owner retained: Callers normalize once from the same config and pass that value into the existing manifest eligibility owner, which still applies disabled-entry, denylist, and restrictive-allowlist rules. (src/plugins/manifest-contract-eligibility.ts:38, 858138db7e15)
  • Transcript session fence retained: The recorder borrows the current entry only to match the admitted session ID, then supplies that ID as expectedSessionId; guarded transcript persistence re-reads and validates it before committing. (src/gateway/server-methods/chat-user-turn-recorder.ts:99, 858138db7e15)
  • Session-copy ownership: Exact SQLite reads decode new row values, while the patch path still clones callback inputs and returned results; identity publication retains transaction-owned decoded values only. (src/config/sessions/session-accessor.sqlite-entry-store.ts:76, 858138db7e15)
  • Focused regression coverage: Added coverage combines disabled/denied plugin owners with an eligible sibling and checks Gateway admission/session-copy behavior against real SQLite-backed fixtures. (src/agents/tool-policy-pipeline.test.ts:309, 858138db7e15)
  • Current-main and related-work check: Current main is 9aa82b1 and does not contain this unmerged branch; the related merged preparation refactor predates this PR and is adjacent rather than a replacement. (9aa82b18253b)

Likely related people:

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

Rank-up moves

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

  • Allow the in-progress exact-head status checks to complete before landing.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-01T02:43:50.546Z sha faa28eb :: needs changes before merge. :: [P3] Remove the release-owned changelog entry

@steipete
steipete merged commit a0868f4 into main Sep 1, 2026
266 checks passed
@steipete
steipete deleted the codex/gateway-turn-preparation-cleanup branch September 1, 2026 03:02
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 1, 2026
* perf(gateway): reduce repeated turn preparation work

* chore: keep turn preparation release notes in PR body
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 P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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