Skip to content

perf(git): reduce first-chat baseline startup - #167936

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-first-chat-send-startup-latency-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-first-chat-send-startup-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

The first chat turn waits on a cold Git baseline worker whose dispatcher imports every Git read implementation, including worktree allocation and registry code that baseline capture never uses. The existing 30-second worker idle expiry lets that cold cost recur on a running Gateway.

User Impact

Cold first-turn startup improves by roughly 300 ms in fresh, large-workspace, and managed-worktree sessions. Baseline preparation is approximately 1.9–2.0× faster. This does not remove all startup delay: session initialization, compaction preflight, and worktree provisioning remain material costs.

Why This Change Was Made

The existing Git worker dispatches each read directly to its lazily loaded owner. Delete the redundant eager dispatcher and unused result type; update the wrapper inventory and test routing to follow the remaining owner. The same leaf functions, identity concurrency limit, cancellation, and filesystem custody remain in use.

Production LOC: −5; tooling: −1 (five files, 40 insertions / 46 deletions). No new runtime owner or cache.

Evidence

A fixed alternating AB/BA campaign ran ten pairs per scenario, with a new Gateway and synthetic state for every first turn. All 60/60 turns completed, appeared in history, and fully shut down. Every paired startup and model-request measurement improved; paired request sizes matched. No samples or outliers were discarded.

Scenario Startup p50 before → after Startup p95 before → after Model HTTP arrival p50 before → after Model HTTP arrival p95 before → after
Fresh session 3,175 → 2,868 ms 3,189 → 2,877 ms 4,230 → 3,925 ms 4,251 → 3,936 ms
6,000 files / 100 skills 3,357 → 3,070 ms 3,402 → 3,113 ms 4,414 → 4,127 ms 4,459 → 4,184 ms
Managed worktree 3,664 → 3,388 ms 3,888 → 3,412 ms 7,321 → 7,047 ms 7,509 → 7,144 ms

Cold Git baseline p50 fell 647 → 329 ms, 643 → 340 ms, and 599 → 316 ms, respectively. Overall startup improves about 8–10%, rather than 1.5×; the owner-level improvement and consistent tail reduction justify the smaller, simpler implementation.

Startup breakdown and measurement method

Fresh-session median spans, in milliseconds:

Component Before After
Dispatch 11 11
Skill authoring 25 25
Reply initialization, including the following workspace/session/baseline work 1,410 1,092
Workspace preparation 29 29
Session initialization 622 620
Git baseline 647 329
Later preparation 1,718 1,728
Skill snapshot 192 197
Compaction preflight 636 642
Base tools / bundled tools 88 / 67 87 / 67
Tool catalog / system prompt assembly 12 / 12 12 / 12
Embedded session runtime 351 349

Managed-worktree preparation itself remains 1,088 → 1,087 ms. Reply context and prompt-body assembly are below 1 ms in the fresh fixture. These spans nest, overlap, and can extend beyond the startup event; they must not be added together.

The rig uses real sessions.create, chat.send, agent.wait, and chat.history with loopback mock inference. Bootstrap, skills, and normal tool preparation remain enabled. Startup is server ACK to onAgentRunStart (first accepted execution activity), not universally the model network call. HTTP arrival is measured separately from client submission; the worktree case includes the initial-message sessions.create flow.

Baseline: 432ade6f500de6cdb0bcd4b0948a07bf466672f1. The exact candidate patch was verified before execution. Node 24.19.0, pnpm 12.7.0. Independent core builds use identical frozen dependency inputs. Two unchanged packages (ai and gateway-protocol) use common complete build artifacts because their bundler partitioned its generated helper nondeterministically; source equality and before/after artifact fingerprints were verified. Both runtime snapshots omit .git, equally excluding development-only plugin discovery.

With ten samples per variant/scenario, the reported p95 is the maximum observation, not a production-tail estimate. Filesystem caches stay in their natural state. Synthetic inference proves startup and request delivery, not external provider latency or a production deployment.

Remote validation and review

blacksmith-testbox, profile openclaw-check, lease tbx_01m4grebdr7ze46m2hpyb0wzkb: baseline/candidate builds, four focused Vitest shards (163.78 s), export guard, and 135 closure/CI-plan cases (68.92 s) passed. The lease disappeared during the changed gate; that incomplete run is not counted as passing.

Authorized AWS fallback, lease cbx_d32aeaa197dd, validation run run_ed158431e45268e5c5a86b105377622b: all commands below passed. Build: 321.3 s; four focused shards: 170.81 s; 135 closure/CI-plan tests: 89.75 s; full validation command: 32m48s.

pnpm install --frozen-lockfile
pnpm build
node scripts/run-vitest.mjs src/infra/git-*.test.ts src/sessions/session-diff*.test.ts src/agents/worktrees/service-branches.test.ts src/gateway/control-ui-session-prs-branch.test.ts
node --import ./scripts/tsx.mjs scripts/check-export-name-collisions.mts
node scripts/run-vitest.mjs test/scripts/eager-import-closure.test.ts test/scripts/pr-wrapper-source-closure.test.ts test/scripts/ci-node-test-plan.test.ts
node scripts/check-changed.mjs --staged
git diff --cached --check

The paired rig ran on the same AWS lease as run_b74466649b24e1694f5805744c804f44, using paired-runtime.mjs compare --pairs 10 --cases fresh,large,worktree: 60/60 passed, command 19m48s, exit 0. Both artifact fingerprints remained unchanged after timing. Earlier sequential timings were excluded as a comparison method because host drift made them unreliable; the complete fixed paired campaign is reported above.

The published commit rebases the reviewed patch onto 5a292d07eb88 without changing its stable patch ID. The affected worker contracts and implementation owners are unchanged from the measured base; the measurements and remote gates above are explicitly pre-rebase evidence.

Independent Codex review returned scoped-clean through P2. No tests were added or changed. No local builds, test suites, or typechecks were run.

Dispatch Git reads lazily from the existing worker and remove the eager read dispatcher. This avoids loading worktree and PR machinery for session baseline capture while preserving each operation owner and lifecycle.

Sixty paired synthetic first turns passed on Crabbox AWS: cold baseline preparation improves roughly 1.9–2.0x and startup drops about 300 ms. Focused regression suites, import/export guards, the full changed-file gate, and independent review passed.
@clawsweeper

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

@steipete
steipete marked this pull request as ready for review October 9, 2026 19:36
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: S labels Oct 9, 2026
@steipete
steipete enabled auto-merge (squash) October 9, 2026 19:38
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The Git worker loads only the implementation needed for each repository read, reducing preparation time before the first chat turn.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A smaller implementation with convincing paired Gateway measurements, preserved contracts, and no actionable review findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied paired AWS campaign exercises baseline capture through real Gateway session creation and chat RPCs with loopback inference, reports all 60 turns completing and entering history, and shows improved startup and model-request arrival across three scenarios. Source comparison supports the explicitly pre-rebase evidence; external provider latency is outside its claim.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Users wait unnecessarily before their first chat turn starts while a cold Git worker loads unrelated repository machinery.
Reason: The paired campaign shows a consistent improvement across three session shapes, and the implementation simplifies an area already maintained by the author without changing product contracts.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main retains the eager dispatcher, the supplied measurements show a consistent startup improvement, and source review found no actionable defect. Required CI is still running.

Priority: P2
Reviewed head: 0751773544e483ea42627214834af4708444ac12

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway captures a checkout baseline before a session starts so later changes can be attributed to that session. Its Git worker performs repository reads while the Gateway retains subprocess supervision, authority, and cleanup.

flowchart TD
  A[First chat turn] --> B[Session baseline capture]
  B --> C[Existing Git worker pool]
  C --> D{Requested repository operation}
  D --> E[Load baseline implementation]
  D --> F[Load other read implementation]
  E --> G[Gateway supervised Git and filesystem reads]
  F --> G
  G --> H[Repository facts returned to caller]
Loading

Technical review

Best possible solution:

Keep operation-specific lazy loading in the existing Git worker and retain the established leaf implementations and host lifecycle.

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

Not applicable as a bug reproduction; this is a performance improvement supported by a paired real-Gateway startup campaign and a source-visible eager import path on current main.

Is this the best way to solve the issue?

Yes. Moving lazy dispatch into the existing worker removes the unnecessary import closure while preserving operation owners, arguments, concurrency, and lifecycle.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced dispatch preserves operation contracts: The pinned introduction replaces the eager dispatcher with direct lazy imports for all seven Git read operations. Each operation retains its existing implementation and arguments; repository identity discovery retains concurrency limit 4. The worker context and filesystem references still wrap dispatch. (src/infra/git-operation.worker.ts:81, 0751773544e4)
  • Current main still needs the optimization: Fetched main still contains the dispatcher that eagerly imports branch discovery, worktree preparation, PR context, and session diff implementations. Comparing the reviewed base with fetched main found no changes to the five touched paths. (src/infra/git-read-operations.runtime.ts:1, e19bcd6bd11e)
  • Original worker ownership intent: History traces the dispatcher to f0fafba. The merged fix: reduce repeated Git work during repository requests #146273 explains that workers perform repository reads while the Gateway retains subprocesses, authority, registry writes, and cleanup; this PR preserves that division. (src/infra/git-operation.worker.ts:3, f0fafba02efd)
  • Measured source remains applicable after rebase: The measured baseline and reviewed merge base have identical worker dispatch, worker contracts and context, baseline implementation, branch reader, repository identity owner, and checkout PR reader. This supports the body's explicitly pre-rebase measurements without treating them as current-head CI. (src/infra/git-operation.worker.ts:119, 5a292d07eb88)
  • Real Gateway startup comparison: The complete supplied PR body, captured with source identity 6eb519c947b639dd145c78f71783162f5033bc239bb7fef82ccfc8c2b5cb6d4d, reports an alternating paired campaign using real sessions.create, chat.send, agent.wait, and chat.history on isolated AWS Gateways with loopback inference. All 60 turns completed, appeared in history, and shut down. Fresh-session startup p50 improved from 3,175 to 2,868 ms, with baseline capture improving from 647 to 329 ms; large-workspace and managed-worktree scenarios also improved.
  • Complete cutover and unchanged lifecycle: The current tree has no references to the deleted dispatcher or removed result type. Wrapper inventory drops the deleted file, and the existing branch regression watch follows the worker. The unchanged host still owns process cancellation, final authority checks, host-work settlement, and temporary-directory cleanup. (src/infra/git-worker.ts:295, 0751773544e4)

PR surface

Source -5, Other -1. Total -6 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 39 44 -5
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 2 -1
Total 5 40 46 -6

Review metrics

Metric Value Why it matters
Production versus test LOC Production −5; tooling −1; tests unchanged The startup optimization reduces production code and adds no test maintenance burden.

Labels

Label changes:

  • add P2: The measured first-turn latency improvement is useful but does not address an urgent broken workflow.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: The measured first-turn latency improvement is useful but does not address an urgent broken workflow.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 3:42 PM ET / 19:42 UTC.

@steipete
steipete merged commit 8161490 into main Oct 9, 2026
217 of 218 checks passed
@steipete
steipete deleted the steipete/perf-micro-first-chat-send-startup-latency-20260919 branch October 9, 2026 19:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
Dispatch Git reads lazily from the existing worker and remove the eager read dispatcher. This avoids loading worktree and PR machinery for session baseline capture while preserving each operation owner and lifecycle.

Sixty paired synthetic first turns passed on Crabbox AWS: cold baseline preparation improves roughly 1.9–2.0x and startup drops about 300 ms. Focused regression suites, import/export guards, the full changed-file gate, and independent review passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts 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