Skip to content

fix(sessions): overlap diff baseline capture with inference - #166797

Closed
steipete wants to merge 6 commits into
mainfrom
codex/stab-first-turn-latency
Closed

steipete wants to merge 6 commits into
mainfrom
codex/stab-first-turn-latency

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every first turn of a session in a git repository waits for the session-diff baseline before the model request starts. In a large repository that is real latency on every new session. On a 52,834-file repository (dev Gateway on main 9aa7455, reply profiler on), reply.capture_session_diff_baseline took 0.8–1.2 s on warm turns, and every first turn spent that time before inference. A cold first turn reached the model only after 4.9 s, versus 2.2 s with this change. In the earlier round of this campaign, on a busier host, the same stage measured 5.3–12.5 s.

The baseline only has to exist before the session can change the workspace. Inference, prompt assembly, and model streaming do not touch files, so blocking them on Git work is unnecessary.

User Impact

  • New sessions in large repositories start talking to the model without waiting on Git: profiled first turns spend 110–140 ms in initialization instead of 0.8–1.2 s (warm) to several seconds (cold) on the baseline.
  • Session diffs stay exact. Any tool that can mutate the workspace waits for the same in-flight baseline before it runs, so a first-turn write is still attributed to the session and pre-existing untracked files are still excluded.

Why This Change Was Made

Capture already ran in a worker; the only problem was that reply initialization awaited it. The baseline owner (src/sessions/session-diff-baseline.ts) now starts capture after authoritative session admission and publishes the in-flight promise through a reply-scoped owner. Inference may overlap capture only where the host itself gates every tool execution. Everything that can change the workspace joins the same promise at its execution owner:

  • Built-in embedded runtime: wrapped tools, host-bound tools, and tools created later through retained host capabilities await the capture before executing. Plain model turns keep the overlap.
  • Native harness backends (Codex app-server) and opaque CLI/ACP backends: the turn is not dispatched until the capture settles (src/agents/harness/selection.ts). The native PreToolUse hook only asserts readiness, so no capture time is spent inside the fixed native hook and relay deadlines. On these runtimes, first-turn latency is unchanged from main.
  • Recognized slash commands and directives (/bash, !, plugin commands, exports, diagnostics, status), reset hooks, and native fast commands join the capture before executing (commands-core.ts and the fast-path owners). Plain model input does not wait there.
  • Registered plugin hooks: the shared hook dispatcher (src/plugins/hooks.ts) joins the capture before invoking any registered callback (including before_model_resolve during model setup and synchronous transcript hooks), so turns without such hooks keep the overlap.
  • Channel-bound ACP reset claims were never consumed; they now settle through the same baseline owner. The ACP binding lookup was extracted into a sibling module, which keeps dispatch-acp.ts at 719 counted lines, under its 730 allowance.
  • sessions.diff readers join an active capture instead of starting one, and reply settlement keeps the dependency.

Capture failure keeps its existing behavior: an unavailable baseline means the session continues without attribution filtering. Capture now passes --no-optional-locks so it never contends with the user's own Git commands. No cache, schema, public config, protocol, or SDK shape was added.

Review history:

  • ClawSweeper found that a first-turn /bash bypassed the barrier, and that waiting inside the native PreToolUse hook could exceed the Codex hook and relay deadlines. The execution-owner design above fixes both, which is why native backends no longer overlap.
  • A landing review then found that a registered before_model_resolve plugin hook could write before the capture settled. That is fixed at the shared hook dispatcher.

Evidence

Live (dev Gateways from main and this head 24e3ddf, fresh state, real OpenAI provider, reply profiler on; CWD = a 52,834-file repository):

first turns in the big repo     main 9aa74552                                         this head
built-in runtime                capture_session_diff_baseline 866–1155 ms before model   lifecycle start 0.68–1.09 s; init 643 ms, no baseline stage
Codex runtime                   capture_session_diff_baseline 812–831 ms before model    1.18–1.47 s (by design, native backends wait for capture before dispatch)
cold first turn, built-in       4.9 s to lifecycle start                              2.2 s (earlier head, same overlap path)

Correctness, live on both runtimes: a first turn whose first action is echo hi > <file> in a small Git repository reports exactly that file as added in sessions.diff; untracked files that existed before the turn are not reported. A live /bash first-turn write could not run on the test Gateway because elevated commands were not allowed for WebChat (tools.elevated.allowFrom.webchat); the regressions below cover that path.

Tests:

  • Focused, session, command, reply, and CLI suites: 251 passed (203 s).
  • Harness, native, ACP, and plugin-hook suites: 445 passed (277 s).
  • New hook regression: 7 passed (24.5 s).
  • Earlier rounds: 1,632 across 103 files.

With the original production code, these fail: the premature-write regressions (/bash, !, plugin commands, plugin hooks, native dispatch, native fast commands, reset hooks, ACP claims), and all four callback-family cases when the shared hook barrier is disabled. Core production and test types, full build, lint, format, the line-cap and assertion ratchets, and the import-cycle check (0) pass. No prompt or tool definitions changed. Autoreview is clean through P2.

Production +388/-158, tests +931/-41, docs +2 (docs/concepts/managed-worktrees.md).

Start the existing baseline capture after session admission without holding the first model request. Retain its promise at embedded and native tool boundaries, including tools materialized later, and join it before opaque backends, queue handoff, diff reads, and turn settlement. Keep read-only diff requests from starting captures and disable optional Git index locks.

Release-note context: large repository sessions can prepare the first reply while preserving pre-agent workspace attribution. Deterministic tests cover held capture, mutation rejection, native and late tool callbacks, and pending diff persistence.
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 2:16 AM ET / 06:16 UTC (Revision 4).

ClawSweeper review

What this changes

The branch overlaps initial workspace diff capture with built-in inference while making tools, commands, plugin callbacks, other runtimes, and diff readers wait for capture.

Example: Start a built-in agent session in a 52,834-file Git repository.

  • Before: The first model request waits 866–1155 ms for workspace baseline capture.
  • After: Inference can start during capture, while first-turn writes remain visible in the session diff.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Measured real-Gateway proof and focused ordering regressions support a worthwhile optimization with the prior blockers resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Current-head live output exercises real dev Gateways and provider turns, demonstrates built-in inference overlap, retains native capture-before-dispatch behavior, and confirms first-write attribution with pre-existing files excluded. Held-capture regressions supplement command and early-hook coverage. The existing persisted baseline and claim formats remain unchanged, so no migration is required.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: First replies in large Git repositories wait for workspace scanning before the model can start.
Reason: The measured delay is substantial, and the existing session-area contributor proposes a bounded optimization that preserves first-write attribution.

Merge readiness

✅ Ready for maintainer review

This PR remains a useful, proven performance improvement. The prior findings are addressed, and the reviewed diff reveals no remaining actionable defect.

Priority: P2
Reviewed head: 24e3ddfa7b3cd9f7909dd326b67da20d2678f1d3

Before merge

None.

Findings

None.

Provenance

  • src/sessions/session-diff.runtime.ts Git optional-lock behavior: original intent not found (unknown: File history was searched, but content-history expansion failed with HTTP 403; no introducing rationale for optional Git locks was established.)
Agent review details

How this fits together

OpenClaw captures the workspace's existing changes so session diffs show what the agent changed. Reply preparation starts that capture, and execution boundaries wait for it before workspace-capable work begins.

flowchart TD
  A[New session turn] --> B[Admit session and start baseline capture]
  B --> C[Capture existing Git changes]
  B --> D[Prepare built-in inference]
  D --> E[Tools and plugin callbacks]
  C --> E
  C --> F[Native CLI and ACP dispatch]
  C --> G[Session diff readers and reply settlement]
Loading

Technical review

Best possible solution:

Keep the existing generation-fenced capture owner and allow overlap only where execution owners can enforce the workspace-write barrier.

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

Not applicable as a functional bug reproduction; the supplied paired Gateway profiling establishes the latency problem, and source confirms the baseline currently precedes inference.

Is this the best way to solve the issue?

Yes. Moving the wait to execution owners preserves the existing attribution contract and avoids consuming native hook deadlines without adding configuration or a competing capture implementation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point. Added test files: 10.

Security

None.

Evidence

What I checked:

  • Pinned introduced diff: Reviewed the merge-base-to-head production and test hunks; the checkout is the original PR head and remained clean. No tests or builds were executed during this read-only review. (24e3ddfa7b3c)
  • One capture owner with retained settlement: Deferred capture reuses the existing single-flight capture and persistence owner; reply settlement awaits its promise. Existing generation checks, settlement CAS, and terminal unavailable behavior remain intact. (src/sessions/session-diff-baseline.ts:251, 24e3ddfa7b3c)
  • Prior early-hook finding resolved: The shared asynchronous hook families await capture before invoking registered handlers. Synchronous before-message-write hooks are prepared at early session preparation and again inside the selected runtime registry. (src/plugins/hooks.ts:630, 24e3ddfa7b3c)
  • Hook regression protects attribution: The new held-capture cases drive actual hook callbacks that write hook-write.txt, verify its absence before capture release, and verify its presence in the resulting real-Git diff; prepared registries and hook-free overlap are covered. (src/sessions/session-diff-hook-capture.test.ts:80, 24e3ddfa7b3c)
  • Prior fixture and extraction findings resolved: The active-capture fixture now uses InternalSessionEntry and a typed patchSessionEntryCore mock. ACP binding lookup was moved into the existing sibling runtime module without changing its account matching. (src/gateway/server-methods/sessions-diff.test.ts:236, 24e3ddfa7b3c)
  • Native deadlines preserved: Non-built-in harnesses await capture before backend dispatch; retained host tools await the bound promise and then check current authority. Native pre-tool callbacks assert readiness rather than waiting inside the relay deadline. (src/agents/harness/selection.ts:215, 24e3ddfa7b3c)

Likely related people:

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

PR surface

Source +230, Tests +890, Docs +2, Other 0. Total +1122 across 38 files.

View PR surface stats
Area Files Added Removed Net
Source 26 386 156 +230
Tests 10 931 41 +890
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 38 1321 199 +1122

Labels

Label changes:

  • 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.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Measured first-turn latency in large Git workspaces makes this a useful improvement with a bounded affected 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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-07T23:21:42.377Z sha 0150def :: blocked before merge. :: [P2] Wait for capture before executing first-turn shell commands | [P2] Accommodate baseline capture in the native relay deadline
  • reviewed 2026-10-08T04:51:19.677Z sha d51bd4a :: needs changes before merge. :: none
  • reviewed 2026-10-08T05:13:53.456Z sha bed20b2 :: blocked before merge. :: [P2] Wait for capture before invoking early model-selection hooks | [P2] Correct the new active-capture regression's fixture types

Keep first-turn inference overlap only for host-gated embedded tools. Join capture before native backend dispatch, direct command effects, and channel-bound ACP turns with armed claims. Preserve unavailable-baseline behavior and attribute first-turn command writes without consuming native hook deadlines.
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 8, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Oct 8, 2026
Gate registered asynchronous hooks in the shared runner before callbacks and their error/timeout policies. Prepare synchronous transcript hooks both before early transcript admission and inside the admitted runtime registry; hook-free model setup still overlaps capture.

Extract the existing capture context into a leaf and migrate its consumers to keep persistence out of plugin startup. Regressions cover real hook writes, diff attribution, prepared registries, and no-hook overlap. Keep hook and ACP files within inherited line allowances without assertion casts.
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 8, 2026
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Closing without merging, by maintainer decision.

Overlapping the session-diff baseline capture with inference is only correct if every pre-inference path that can run configured code or touch the workspace joins the capture first. Five review rounds each found another such path:

  • first-turn /bash
  • the Codex native hook deadline
  • plugin hooks
  • internal agent:bootstrap hooks
  • provider and channel callbacks

The final, safe design joins the capture before any registered callback. The bundled OpenAI provider has a policy callback, so in the default configuration the capture is back on the pre-model path.

Live side-by-side on a 52,834-file repository (real OpenAI provider, reply profiler on):

                       main 905a74d1        latest PR head
first-turn start       0.72–1.62 s          0.73–1.24 s
capture before model   230–858 ms           215–800 ms

The safe version therefore brings no measurable speedup in the common configuration, while adding about 760 production lines and a cross-cutting ordering invariant. Main's blocking capture stays. Warm capture is now about 0.25–0.35 s; a future change could make the capture itself cheaper instead of moving it.

@steipete steipete closed this Oct 8, 2026
@RomneyDa
RomneyDa deleted the codex/stab-first-turn-latency branch October 22, 2026 05:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime 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. size: XL 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