Skip to content

refactor(agents): reduce per-turn policy and tool preparation - #134246

Merged
steipete merged 3 commits into
mainfrom
codex/gateway-turn-preparation-perf
Aug 31, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/gateway-turn-preparation-perf

Conversation

@steipete

@steipete steipete commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Warm chat turns repeat policy and authentication discovery, build coding tools that are immediately discarded, traverse tool schemas more than necessary, and deep-copy unrelated session entries during admission and transcript handling. This adds preparation work before the model can respond, especially with larger session stores.

Why This Change Was Made

Reuse the native execution policy within each Codex tool build, resolve absent-search policy only when its persistent-policy callback needs it, and consume prepared model/auth facts before discovering them again. Remove discarded coding-tool construction and redundant factory forwarding, and combine schema validation traversal while preserving numeric-overflow diagnostics.

Admission and transcript consumers use the existing borrowed-read option. Initial session resolution still owns detached entries; all later lookups and post-await session fences remain. This keeps listing visibility, private exact history, provisioning, validation, and lifecycle behavior unchanged. The rebase preserves main's separate policy/execution agent identities and catalog-pricing precedence. No new configuration, dependencies, caches, or storage/schema changes.

Related: #133782, #133184. These earlier preparation improvements cover different work.

User Impact

Less repeated per-turn work and 114 fewer production lines (+202/−316). Tests: +232/−84, net +148. Existing tools, policy decisions, session history, and model selection retain their behavior.

The first matched live experiment reduced median preparation from 115.71 to 96.55 ms (16.6%), but did not improve complete-reply latency or aggregate CPU. The additional session-copy change reduced isolated 1,000-row lookup time from 8.613 to 0.835 ms and fixture-row copies across two live turns from 14,000 to 8,000. It did not establish another live latency improvement: small-store preparation stayed near 95.9 ms; with 1,000 retained fixtures, median preparation was 187.09→191.76 ms and complete reply 1,390.55→1,492.55 ms. The candidate's 782.79 ms preparation outlier is included. These serial shared-machine measurements do not establish an end-to-end speedup, and the two comparisons must not be added together.

Evidence

  • Real loopback development Gateway with OpenAI API-key authentication and openai/gpt-5.6-luna, low reasoning, fast mode off. Matched stopped-state snapshots, persistent WebSocket client, fresh process per workload, warmups, CPU profiles, and separate copy/allocation instrumentation. First pass: 152 comparison turns (104 measured); session-copy continuation: 144 turns (96 measured). All measured replies matched the expected response. Plain reply, file-read, and session-status tool smoke passed.
  • An initial large-store experiment was trimmed to 500 rows by maintenance. The final pair verified all 1,000 fixtures remained in both builds. Temporary settings and synthetic fixtures were removed afterward. No builds or test suites overlapped timed samples.
  • 1,237 focused passing cases across the two implementation phases, full first-pass build, final runtime build, and changed-code gates. The copy-count regression failed on the original implementation before passing with borrowed reads.
  • After integration with main, 359 cases across nine files passed: Codex dynamic tools and connection preparation; model resolution and pricing overrides; schema projection; Gateway single-row projections, admission/session binding, reply dispatch, and history. Run with node scripts/run-vitest.mjs and those focused files.
  • The timeout-hook fixture no longer requires an auth-store lookup for explicit model metadata; auth-isolation and real HTTP timeout assertions remain. Its seven cases and 12 model-generation/discovery/forward-compatibility siblings passed after the stale cleanup assertion was removed.
  • Hosted CI also exposed two wall-clock parser-performance assertions on a loaded runner. Replaced them with call-through work bounds, retaining the same fixtures and output checks; 197 cases across the two files passed. In-memory regression mutations raise preceding-prefix slices from 2 to 600 and exceed the reasoning-parser input budget after 938 bytes. No timeouts were increased and no production parser code changed.
  • Fresh Codex autoreview: no accepted/actionable findings at its configured P0 threshold. Independent integration audit verified retained policy ownership and pricing. Direct Codex source inspection covered codex-rs/app-server/src/request_processors/turn_processor.rs (turn admission), codex-rs/core/src/client.rs (WebSocket lifetime), and app-server protocol thread start/resume contracts. No Codex protocol changes.

An exact-reader replacement was rejected because private companion history intentionally reads hidden current-session rows and exact access has different provisioning/validation contracts. The retained borrowed mode preserves those contracts. Remaining follow-up: profile other full-store consumers and filesystem-watcher work; full-store enumeration remains in this PR.

@steipete steipete self-assigned this Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 31, 2026 16:03
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling extensions: codex size: L maintainer Maintainer-authored PR labels Aug 31, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 31, 2026, 1:20 PM ET / 17:20 UTC.

ClawSweeper review

What this changes

This PR removes repeated per-turn policy, tool, model, schema, and session-copy preparation while preserving existing Gateway session checks and Codex dynamic-tool behavior.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer review. No concrete introduced defect was found in the inspected owner paths, but the native Codex environment-selection contract could not be independently checked because the required sibling ../codex checkout is absent in this read-only environment.

Priority: P3
Reviewed head: f759357e377ab1b57d922cda0378e0bdd2d943f3
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has meaningful source and supplied runtime evidence, but the Codex-backed compatibility review cannot be completed in this environment.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the supplied body nevertheless describes an after-fix loopback Gateway run. The remaining gap is reviewer-side Codex source access, not missing contributor proof.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the supplied body nevertheless describes an after-fix loopback Gateway run. The remaining gap is reviewer-side Codex source access, not missing contributor proof.
Evidence reviewed 7 items Native policy is resolved once within the dynamic-tool build: The changed builder computes one native execution-policy value and forwards it through tool construction and all shell-surface decisions, rather than independently resolving it in each helper.
Session borrowing preserves later owner reads: Admission borrows the targeted session for a routing check, while reply dispatch extracts scalar bindings and rereads the session before later transcript work.
Session-store owner supports non-cloning reads: The Gateway session-store resolver already accepts clone: false; the proposed callers use that existing option rather than changing storage or migration semantics.
Findings None None.
Security None None.

How this fits together

Gateway chat admission prepares a session, model, and tool surface before the provider turn begins, then reply dispatch rechecks session ownership before writing transcripts. The Codex plugin converts those prepared facts into app-server dynamic tools.

flowchart LR
  A[Incoming chat turn] --> B[Gateway admission]
  B --> C[Session and model preparation]
  C --> D[Codex dynamic tools]
  D --> E[Provider turn]
  E --> F[Reply dispatch and transcript]
  C --> G[Session ownership rechecks]
Loading

Decision needed

Question Recommendation
Should a reviewer with the required Codex checkout complete the explicit-empty-environment contract check before this refactor is merged? Complete the direct Codex check: Verify the app-server environment-selection and dynamic-tool contracts against this exact PR head before merge.

Why: The changed native execution gate directly depends on Codex app-server behavior, and repository policy requires the acting reviewer to inspect that source personally.

Before merge

  • Resolve merge risk (P1) - Merging relies on the Codex app-server interpretation of an explicit empty environment selection; that dependency contract needs direct reviewer inspection before a merge recommendation.
  • Complete next step (P2) - The remaining blocker is independent Codex dependency-contract inspection, not a narrow repair that an automated worker can safely make.
Agent review details

Security

None.

PR surface

Source -114, Tests +148. Total +34 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 203 317 -114
Tests 8 231 83 +148
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 434 400 +34

Review metrics

Metric Value Why it matters
Production versus test LOC production +202/-316 (net -114); tests and test support +232/-84 (net +148) The refactor is net-negative in production while adding focused coverage for retained policy and session invariants.

Stored data model

Persistent data-model change detected: unknown-data-model-change: packages/ai/src/providers/tool-schema-json-projection.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Verify the Codex contract first (recommended)
    Confirm that explicit empty environments retain the intended no-native-tools behavior before merge.
  2. Pause pending direct inspection
    Keep this PR open until a reviewer can inspect the required Codex source contract.

Technical review

Best possible solution:

Retain the single prepared policy flow, but complete an exact-head review in an environment containing the required Codex checkout and verify that explicit empty environments still suppress native shell and filesystem tools.

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

Not applicable: this is a performance refactor, not a report of broken existing behavior. The supplied PR body describes real Gateway runs, but this read-only review did not execute them.

Is this the best way to solve the issue?

Unclear until the direct Codex contract check is complete. The inspected OpenClaw changes keep the policy fact local to a tool build and retain later session rereads, which is the appropriate owner-boundary shape.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P3: This is an internal preparation-performance refactor with no demonstrated user-facing regression.
  • merge-risk: 🚨 compatibility: Native Codex tool exposure depends on an external app-server environment-selection contract that remains unverified by this reviewer.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository state identifies the author as a MEMBER, so the external-contributor proof gate does not apply; the supplied body nevertheless describes an after-fix loopback Gateway run. The remaining gap is reviewer-side Codex source access, not missing contributor proof.

Evidence

What I checked:

Likely related people:

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

  • Have a reviewer with the required sibling Codex checkout verify the explicit-empty-environment behavior on this exact head.

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 (2 earlier review cycles)
  • reviewed 2026-08-31T16:12:20.560Z sha e711f55 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-31T16:35:30.745Z sha 3798ec5 :: needs maintainer review before merge. :: none

@steipete steipete changed the title improve(agents): reduce per-turn policy and tool preparation refactor(agents): reduce per-turn policy and tool preparation Aug 31, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Completed the direct Codex source check requested by the review and its rank-up move. I personally inspected the clean sibling checkout at the publicly available Codex commit 94cbbddafc17:

  • TurnStartParams distinguishes omitted environments from an explicit empty selection. The request resolver preserves Some([]), and turn override construction passes explicit selections through without replacing them with the local environment.
  • Native shell registration requires an environment. Apply-patch and image tools retain the same environment condition. OpenClaw still sends an explicit empty selection when native execution is disabled, and still requires the configured sandbox exec-server integration plus sandbox tool permissions before enabling that surface.
  • Dynamic tool execution registers its response channel against the active turn and waits for the host response. This refactor retains OpenClaw's canonical host tool binding/execution boundary.

The reused fact is scoped to one buildDynamicTools call and is selected with the retained policyAgentId; it is not a cross-turn policy cache. The separate native-surface gate, node-host denial, sandbox requirements, tool exclusions, and live execution authority remain. The integrated dynamic-tool/connection tests passed, including retained-owner restrictions and null-versus-unresolved sandbox handling. This resolves the source-access limitation in ClawSweeper's environment; no contract mismatch was found.

The stored-data alert for packages/ai/src/providers/tool-schema-json-projection.ts is a false positive: that module serializes and validates an in-memory model-request tool schema. It has no persistent store access, and the patch changes no database schema, migration, or persistence semantics. The changed-code storage guards also passed.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 31, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Final candidate: f759357. Production is unchanged from the integrated runtime tested at e711f55.

  • pnpm build passed.
  • node scripts/check-changed.mjs --base ace8a13f19ccc2805b3d458026de3ab4bbbd8878 --head HEAD passed all changed-code gates (core/plugin production and test types, lint, formatting, imports/exports and storage guards).
  • node scripts/run-vitest.mjs extensions/codex/src/app-server/dynamic-tool-build.test.ts extensions/codex/src/app-server/run-attempt-connection.test.ts src/agents/embedded-agent-runner/model.test.ts src/agents/embedded-agent-runner/model.forward-compat.errors-and-overrides.test.ts src/agents/tool-schema-projection.test.ts src/gateway/session-utils.single-row-cache.test.ts src/gateway/server-methods/chat-send-session-binding.test.ts src/gateway/server-methods/chat-send-reply-dispatch.test.ts src/gateway/server-methods/chat-history-handler.test.ts passed: 359 cases across nine files.
  • Rebuilt loopback Gateway: health and dashboard HTTP checks passed; real OpenAI API-key turns returned the expected plain reply, read the workspace fixture through a tool, and reported openai/gpt-5.6-luna through session_status. These are behavioral smoke checks, not latency samples.
  • Fresh Codex autoreview was scoped-clean at the configured P0 threshold. Independent integration audit confirmed main's policy-owner/execution-agent split, pricing precedence, and both sets of session projection tests were preserved.

The PR body reports the measured improvements and negative results. Production remains +202/−316 (net −114); tests +232/−84 (net +148). The exact-reader alternative was removed because private history and provisioning/validation contracts differ. Existing borrowed reads preserve those contracts and the post-await fence. No end-to-end speedup is claimed.

CI recovery: a later draft-state run canceled the ready-state CI and skipped its own jobs; the ready-state run was rerun on the original candidate commit. Dependency detection also returned a GitHub API 500 and its failed job was rerun. No gates were bypassed. Follow-up: examine the draft/ready event ordering in CI concurrency separately from this runtime refactor.

CI also exposed a stale timeout-fixture cleanup assertion requiring ensureAuthProfileStore to run for explicit model metadata. Removed that obsolete requirement and corrected the fixture comment; all isolation and actual timeout/HTTP assertions remain. Reproduced seven failures before the test correction; all seven cases plus 12 model-resolution siblings then passed. Production code is unchanged by this correction.

The test-only follow-up also passed node scripts/check-changed.mjs -- src/agents/embedded-agent-runner/model.provider-hooks.timeout.test.ts src/agents/embedded-agent-runner/model.fixture.test-support.ts and a fresh complete-candidate Codex autoreview at P0. Direct Codex runtime-contract evidence and the request-schema/storage clarification are recorded in #134246 (comment).

Landing-tooling follow-up: temporary materialization of the current-main wrapper omitted scripts/lib/record-shared.mjs, which review-artifacts.mjs imports. The failed operation lock was recovered only after its processes were gone; the complete trusted canonical scripts/pr validated the new-head artifacts successfully. No source-trust or merge gate was bypassed.

Read the refreshed ClawSweeper review for exact head f759357e377ab1b57d922cda0378e0bdd2d943f3 (17:20 UTC), including its rank-up move. It reports no introduced code/security defect and repeats the reviewer-side absence of a sibling Codex checkout. Personally rechecked the clean sibling checkout at public Codex 94cbbddafc1776d5e377bca1b05932c697e82238: turn.rs:177-184 distinguishes omitted sticky environments from explicit empty selection; request_processors.rs:615-665 preserves Some([]); spec_plan.rs:1085-1100 and 1245-1267 gate native shell, apply-patch, and image tools on environment presence. The follow-up commits change tests only, so the exact PR runtime remains the directly inspected implementation. The required dependency check is complete; the stored-data alert concerns in-memory model-request schema projection, with no persistent schema or migration change.

CI also exposed two fixed wall-clock performance limits on a loaded runner. Replaced them with deterministic parser-work budgets; all 197 cases passed with their original fixture/output checks. Mutation probes demonstrate the regression guards: preceding-prefix slices rise from 2 to 600 without cached trust, and whole-prefix reasoning reparsing breaches its input budget after 938 bytes. Changed-code gates completed after type/lint corrections; final complete-candidate autoreview is clean at P0 (0.96). No production parser code changed or timeouts increased.

Exact-head hosted CI is now complete and green for f759357e377ab1b57d922cda0378e0bdd2d943f3: https://github.com/openclaw/openclaw/actions/runs/33418374940. The normalized PR check rollup is also green (zero pending). Both previously failing jobs passed on this run. Native prepare and merge follow.

@steipete
steipete merged commit 6fc1c2d into main Aug 31, 2026
240 checks passed
@steipete
steipete deleted the codex/gateway-turn-preparation-perf branch August 31, 2026 17:43
@steipete

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
…aw#134246)

* perf(agents): reduce repeated turn preparation

* test(agents): keep timeout proof independent of auth discovery

* test(parsers): measure prefix work without wall-clock limits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: codex gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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