Skip to content

improve(codex): reduce startup CPU for large rollouts - #138784

Merged
steipete merged 1 commit into
mainfrom
codex/team-codex-startup-scan-20260904
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/team-codex-startup-scan-20260904

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves unnecessary startup CPU when a Codex conversation's token snapshot sits behind a large rollout record, or its latest usage needs a context window from an older record.

Why This Change Was Made

Use native Buffer reverse newline search inside the existing 64 KiB reader. It reconstructs and parses the same complete records, preserving latest usage, older windows, short reads, descriptor cleanup, and the current generation checks before binding clears. The loop stops when its prefix is empty because negative Buffer offsets wrap around.

Production is +5/-3 (net +2) for the native-search loop and its termination comment. The existing older-window test becomes three boundary cases, +25/-24 (net +1).

User Impact

Large or sparse-token rollouts require less scan CPU when resuming a Codex conversation. Large-record JSON decoding and parsing remain synchronous, so this is a bounded startup improvement.

Evidence

  • Integrated on f325f4f58d44f9ef1326743c664c603432894b71, retaining fix(codex): preserve native threads after interrupted compaction #138473's generation fences. All 140 tests across three files passed: startup binding, connection preparation, and binding-store ownership. Coverage includes byte 0/1/65,535, split UTF-8, CRLF, malformed/unterminated records, short reads, path/symlink rejection, revoked authority, predecessor-generation lease races, and cancellation cleanup.
  • Production and test extension types, scoped typed lint, and formatting pass. Independent Codex P2 review of this integrated diff is clean. The original-base required static checks also passed; unchanged broad checks were not repeated during this integration.
  • Paired real-filesystem owner probe on original 05a236c7 versus this exact scan change: four variants, three samples each, Node 26.8.1 on a contended macOS host. With a 32 MiB unrelated record, median process CPU was 405→270 ms for an older window, 354→290 ms for a large trailing record, and 403→293 ms with discovery. All twelve results, read counts/bytes, and JSON parse counts/characters matched; the complete-tail control retained one 64 KiB read. The reader/parser prefix is byte-identical on the integration base.
  • The probe uses the existing in-memory binding adapter and excludes SQLite/lease contention. It is not a full Gateway/native startup measurement. Host contention prevents portable wall-time claims; candidate heartbeat gaps still reached 626 ms. Codex 0.153.0's actual token/window and JSONL producer contracts were inspected directly, including legal absent context windows. Native main c57e3632 now pins 0.153.4; direct inspection of that exact upstream release confirms the six token/rollout producer files remain byte-identical. This qualifies these contracts, not the entire runtime.

Earlier fixture-padding, lint/type, and local command-selection failures are retained in the proof record and corrected; no test deadline or assertion outcome was relaxed. Separate follow-ups cover large-record parsing, the preexisting legacy session-file reader, and opt-in compressed rollouts.

Exact-head CI run 33938705423 completed successfully on f8b33a290f24d2e950455f61ae7e10c4a0d2ec4b (36 successful jobs, 17 skipped).

@steipete steipete self-assigned this Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 4, 2026, 10:43 PM ET / September 5, 2026, 02:43 UTC.

ClawSweeper review

What this changes

The PR reduces CPU spent scanning Codex conversation files during resume by using native reverse newline search and expanding chunk-boundary coverage.

Merge readiness

✅ Ready for maintainer review

Keep open: the CPU optimization remains absent from the reviewed main revision, and the focused patch has no blocking correctness findings. The supplied measurements support its deliberately limited performance claim.

Priority: P2
Reviewed head: f8b33a290f24d2e950455f61ae7e10c4a0d2ec4b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with useful boundary coverage and proportionate filesystem measurements; no actionable patch defect was identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.
Evidence reviewed 12 items Verified introduced change and merge result: The merge-base-to-head delta changes only the newline-search loop and its existing older-window test. The recorded test merge has the pinned base followed by the exact PR head as parents; its production diff retains the same narrow change.
Optimization remains necessary on reviewed main: The fetched main revision still walks every byte in JavaScript. Its complete startup-binding module is identical to the PR merge-base version, so current-main drift does not establish redundancy.
Reader and downstream ownership preserved: Complete-module inspection confirms unchanged short-read filling, fragment reconstruction, latest-field selection, JSON parsing, and descriptor cleanup. Connection preparation calls the guard at line 425; projected-prompt preparation also calls it at run-attempt-prompt.ts:443. Both retain generation checks, and session-binding.ts:610 revalidates immediately before the store update.
Findings None None.
Security None None.

How this fits together

The Codex plugin inspects saved native conversation files before reusing a thread. Its startup guard combines token usage and context-window information, then preserves or rotates the saved thread binding.

flowchart TD
  A[Conversation resume] --> B[Saved thread binding]
  B --> C[Codex conversation file]
  C --> D[Reverse chunk reader]
  D --> E[Token usage and context window]
  E --> F{Existing budget checks}
  F --> G[Reuse saved thread]
  F --> H[Generation-checked rotation]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +2, Tests +1. Total +3 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 5 3 +2
Tests 1 25 24 +1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 30 27 +3

Review metrics

Metric Value Why it matters
Production versus test LOC Production net +2; tests net +1 The production growth expresses native-search termination and its negative-offset invariant; test growth replaces one case with three boundary cases without adding a production seam.

Technical review

Best possible solution:

Keep one startup inspection path with native byte search, complete-record parsing, and unchanged token-budget, filesystem, and generation safeguards.

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

Yes: placing a large record between the file tail and required token/window information exercises the per-byte scan still present on reviewed main. The supplied filesystem comparison measures that scenario; this reviewer did not rerun OpenClaw.

Is this the best way to solve the issue?

Yes, for the stated CPU-only improvement: replacing byte iteration inside the existing reader avoids a competing parser, new dependency, or early search cutoff. Large-record decoding and parsing remain separate work.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded startup-performance improvement for large Codex conversations, without evidence of an urgent functional regression.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.
  • 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. Sufficient (live_output): The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.

Label justifications:

  • P2: This is a bounded startup-performance improvement for large Codex conversations, without evidence of an urgent functional regression.
  • 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. Sufficient (live_output): The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured paired real-filesystem probe exercises the startup-binding reader with large records and reports identical decisions and I/O accounting with reduced process CPU. This supports the scan-only claim, not SQLite contention, whole-Gateway startup, or portable wall-time improvements.

Evidence

What I checked:

  • Verified introduced change and merge result: The merge-base-to-head delta changes only the newline-search loop and its existing older-window test. The recorded test merge has the pinned base followed by the exact PR head as parents; its production diff retains the same narrow change. (extensions/codex/src/app-server/startup-binding.ts:276, 3bec17bbb77e)
  • Optimization remains necessary on reviewed main: The fetched main revision still walks every byte in JavaScript. Its complete startup-binding module is identical to the PR merge-base version, so current-main drift does not establish redundancy. (extensions/codex/src/app-server/startup-binding.ts:277, 116c6c3be399)
  • Reader and downstream ownership preserved: Complete-module inspection confirms unchanged short-read filling, fragment reconstruction, latest-field selection, JSON parsing, and descriptor cleanup. Connection preparation calls the guard at line 425; projected-prompt preparation also calls it at run-attempt-prompt.ts:443. Both retain generation checks, and session-binding.ts:610 revalidates immediately before the store update. (extensions/codex/src/app-server/run-attempt-connection.ts:425, f8b33a290f24)
  • Meaningful boundary coverage: The replacement table covers newline positions 0, 1, and 65,535, split multibyte text, CRLF, malformed records, and optional terminal newlines through the real filesystem reader. Its rotation assertion requires combining newer usage with the older window. Existing tests retain direct-path, short-read, native-ownership, and cancellation coverage; no OpenClaw tests were executed during this review. (extensions/codex/src/app-server/startup-binding.test.ts:486, f8b33a290f24)
  • Captured real-filesystem performance evidence: The supplied PR body reports four paired scenarios with three samples each on Node 26.8.1/macOS. For 32 MiB records, median process CPU changed from 405 to 270 ms, 354 to 290 ms, and 403 to 293 ms; results, read counts, bytes, and parse counts matched. The control retained one 64 KiB read. The body explicitly excludes SQLite/lease contention and whole-Gateway timing, and reports 140 passing owner/sibling tests. These are contributor-reported observations from captured context revision 1a0ae27e782657ccce10891847573912fc199839b13f3065fd667f76a716fab4, not reviewer-run benchmarks. (f8b33a290f24)
  • Affirmative Codex dependency signal: The production parser consumes Codex token_count payloads, last_token_usage, and model_context_window. This directly establishes the upstream-contract inspection requirement; it is not inferred from the plugin name. (extensions/codex/src/app-server/startup-binding.ts:308, f8b33a290f24)

Likely related people:

  • steipete: 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 bc55512 into main Sep 5, 2026
112 checks passed
@steipete
steipete deleted the codex/team-codex-startup-scan-20260904 branch September 5, 2026 02:52
@steipete

steipete commented Sep 5, 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 5, 2026
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* refs/remotes/origin/main: (602 commits)
  fix(plugins): trace trust refusals and repair legacy provenance (openclaw#138746)
  perf(sqlite): reuse compiled plugin state point reads (openclaw#138758)
  refactor: type chat prefetch dependencies and clean loading tests (openclaw#138793)
  ci: reduce Doctor test startup and core lint jobs (openclaw#138796)
  feat(update): retain run history and share outcome reports (openclaw#138690)
  chore(deps): update @openclaw/fs-safe to 0.8.1 (openclaw#138500)
  fix: preserve global board ownership from pinning to notifications (openclaw#138675)
  fix(gateway): deliver session catalog updates from slow hosts (openclaw#138674)
  perf(sessions): index pending conversation replies (openclaw#127182)
  perf(auth): reuse ordered provider alias entries (openclaw#138805)
  docs(diagnostics): clarify whole-process CPU metrics (openclaw#138804)
  perf(memory): narrow source reads and stream embedding cache rows (openclaw#138766)
  fix: allow older source on newer Testbox checkouts (openclaw#138782)
  fix(agents): preserve recovered task progress and lifecycle ownership (openclaw#138785)
  perf(codex): reduce rollout tail scan CPU (openclaw#138784)
  perf(gateway): stop projecting history deltas at the byte budget (openclaw#138655)
  fix(build): bound native declaration inputs to checkout (openclaw#138742)
  fix(cli): preserve foreground Gateway argument handling (openclaw#138765)
  fix(ui): align task toolbar with side-panel tabs (openclaw#138769)
  fix(logbook): drain accepted work before closing SQLite (openclaw#138754)
  ...

# Conflicts:
#	src/agents/embedded-agent-runner/compact.queued.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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