Skip to content

perf(sessions): index pending conversation replies - #127182

Merged
steipete merged 1 commit into
mainfrom
codex/fix-conversation-turn-reply-index
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/fix-conversation-turn-reply-index

Conversation

@steipete

@steipete steipete commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #127173. Every exactly correlated conversation reply previously copied, filtered, and sorted the process-wide pending-turn registry before matching its outbound message ID. Completing N unique pending turns visited N(N+1)/2 entries synchronously on the Gateway ingress thread.

Why This Change Was Made

Index pending turns by the exact agent and outbound message ID at the existing pending-turn lifecycle owner. Maintain collision buckets during outbound-ID replacement, and remove membership on completion, timeout, cancellation, and abort. Select the oldest eligible reply from its bucket while preserving agent, session, conversation, thread, claim, and transcript-durability checks.

The primary registry still owns cancellation by turn ID. The secondary index is bounded by active waiters and is cleared through their existing settlement and Gateway restart lifecycle. No configuration or storage-schema change is involved.

User Impact

Correlated reply bursts avoid global scans and temporary arrays/sorts, reducing synchronous ingress work and allocation pressure. Reply routing, cancellation, retry behavior, and durable capture remain unchanged.

Evidence

  • Rebased head: be9686c20bdccf1e00042b85a492d68d8424db0e. git range-diff confirms the original patch is unchanged; the production owner is byte-identical to the reviewed source.

  • 83 focused tests passed across pending-turn correlation, reply capture, Gateway turn execution, Gateway methods, and portal HTTP proxy coverage:

    OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs \
      src/sessions/conversation-turns.test.ts \
      src/auto-reply/reply/conversation-turn-capture.test.ts \
      src/gateway/conversation-turn.test.ts \
      src/gateway/server-methods/conversations.test.ts \
      src/gateway/portals/portal-http-proxy.test.ts
  • Changed-file formatting, production/test typechecks, lint, boundary/storage guards, dead-export scans, and import-cycle checks passed:

    node scripts/check-changed.mjs -- \
      src/sessions/conversation-turns.ts src/sessions/conversation-turns.test.ts
    git diff --check origin/main...HEAD
  • Direct source-level 1,000-reply regression: main visits 500,500 global registry entries; the candidate visits zero. All replies match correctly, and both registries are empty after completion and restart. The zero-scan assertion fails on main and passes on the candidate. The harness redirects imports only to isolated copies of the same normalization/singleton helpers; it is an owner-level runtime proof, not a live-channel run.

  • Fresh independent Codex autoreview: no actionable P0-P2 findings. Independent lifecycle review also found no blocker.

  • The old failed CI job used a released ephemeral port in an unrelated portal test. This rebase includes its canonical repair in fix: keep portal retry-page tests on an owned target port #130920; the portal suite now passes.

ClawSweeper findings and rank-up moves

The equal-timestamp reverse-assignment concern was checked against the sole production registrar in src/gateway/conversation-turn.ts: it registers and immediately assigns the prepared outbound ID without an intervening await, and never reassigns it. A transport ID mismatch cancels the turn. Bucket insertion therefore retains registration order in the real flow. An extra registration ordinal and reverse-assignment-only test are intentionally skipped; existing collision, replacement, and lifecycle coverage remain.

Production: +51/-17, net +34. Tests: +145. The added state is the lifecycle-owned index needed to avoid global scans; a channel-local cache or linear scan would not fix the owning bottleneck.

@clawsweeper

clawsweeper Bot commented Aug 21, 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 21, 2026 12:26
@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 21, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. 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 Aug 21, 2026
@clawsweeper

clawsweeper Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 11:06 PM ET / September 5, 2026, 03:06 UTC.

ClawSweeper review

What this changes

Index pending conversation replies by agent and outbound message ID to avoid scanning unrelated waiters while preserving reply matching and cleanup.

Merge readiness

⛔ Blocked before merge - 1 item remains

The bottleneck remains on current main and v2026.9.1. The production caller resolves the prior ordering concern, and no actionable correctness findings remain.

Priority: P2
Reviewed head: be9686c20bdccf1e00042b85a492d68d8424db0e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level performance repair with useful regression coverage and no remaining actionable finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The contributor live-proof gate does not apply to this maintainer-authored internal optimization. The supplied source-owner run exercises indexed claim/completion and reports correct matching and cleanup; it is supplemental performance evidence, not a live-channel run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The contributor live-proof gate does not apply to this maintainer-authored internal optimization. The supplied source-owner run exercises indexed claim/completion and reports correct matching and cleanup; it is supplemental performance evidence, not a live-channel run.
Evidence reviewed 11 items Verified introduced scope: The merge-base-to-head patch changes only the pending-turn owner and its tests. The test merge has the pinned main and head as its two recorded parents, and its result preserves that same scope.
Current main still scans every waiter: The current implementation materializes pendingTurns.values(), filters and sorts candidates, then checks the outbound ID. The linked issue describes this exact path: #127173.
Latest release retains the bottleneck: The v2026.9.1 source contains the same global scan. The tag resolves to the supplied release commit, so this optimization is not already present in that release.
Findings None None.
Security None None.

How this fits together

The Gateway registers a waiter when an agent sends a conversation message and requests its reply. Incoming channel messages pass through correlation and durable capture before either completing that waiter or continuing ordinary dispatch.

flowchart TD
  A[Conversation turn request] --> B[Register waiter and outbound ID]
  B --> C[Exact reply index]
  D[Incoming channel reply] --> C
  C --> E{Eligible live waiter?}
  E -->|Yes| F[Durable reply capture and cleanup]
  F --> G[Reply returned to waiting agent]
  E -->|No| H[Ordinary inbound dispatch]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +34, Tests +145. Total +179 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 51 17 +34
Tests 1 145 0 +145
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 196 17 +179

Review metrics

Metric Value Why it matters
Production versus test LOC Production +51/-17, net +34; tests +145/-0 Production growth maintains the lifecycle-owned index; removing sorting alone would retain the global scan.
Reported registry work 1,000 replies: 500,500 global visits before, 0 after The recorded operation counts demonstrate the targeted improvement without implying a general latency guarantee.

Stored data model

Persistent data-model change detected: serialized state: src/sessions/conversation-turns.ts, unknown-data-model-change: src/sessions/conversation-turns.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #127173
Summary: This PR is the implementation candidate for the linked global-scan issue; the portal fixture repair addresses a separate test failure.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep the index in the pending-turn lifecycle owner; its additional state enables exact lookup while the primary registry preserves cancellation by turn ID.

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

Yes, from current source: completing N distinct pending turns enumerates N(N+1)/2 registry entries. The supplied owner-level run corroborates this; no runtime reproduction was executed during this read-only review.

Is this the best way to solve the issue?

Yes. Indexing at the shared waiter owner removes the bottleneck for every caller and keeps cleanup centralized; a channel-local cache would duplicate ownership, and removing sorting would still scan unrelated waiters.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The contributor live-proof gate does not apply to this maintainer-authored internal optimization. The supplied source-owner run exercises indexed claim/completion and reports correct matching and cleanup; it is supplemental performance evidence, not a live-channel run.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, 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: This fixes a source-proven synchronous scaling bottleneck during concurrent conversation replies.
  • 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 contributor live-proof gate does not apply to this maintainer-authored internal optimization. The supplied source-owner run exercises indexed claim/completion and reports correct matching and cleanup; it is supplemental performance evidence, not a live-channel run.

Evidence

What I checked:

  • Verified introduced scope: The merge-base-to-head patch changes only the pending-turn owner and its tests. The test merge has the pinned main and head as its two recorded parents, and its result preserves that same scope. (src/sessions/conversation-turns.ts:58, be9686c20bdc)
  • Current main still scans every waiter: The current implementation materializes pendingTurns.values(), filters and sorts candidates, then checks the outbound ID. The linked issue describes this exact path: Conversation reply correlation scans the full pending-turn registry #127173. (src/sessions/conversation-turns.ts:202, 790fbf0304a6)
  • Latest release retains the bottleneck: The v2026.9.1 source contains the same global scan. The tag resolves to the supplied release commit, so this optimization is not already present in that release. (src/sessions/conversation-turns.ts:202, ad6fe23aecb9)
  • Prior ordering finding resolved by caller evidence: Repository-wide call-site inspection finds one production registrar. It registers and immediately assigns the prepared outbound ID without yielding; a transport mismatch cancels instead of reassigning. Bucket insertion therefore follows registration order in production, supporting the explicit skip of both prior rank-up moves in perf(sessions): index pending conversation replies #127182 (comment). The older reviewed SHA was unavailable locally, so patch identity across reviews was not independently established. (src/gateway/conversation-turn.ts:345, be9686c20bdc)
  • Lifecycle ownership and matching preserved: Settlement removes index membership before deleting the primary entry; replacement removes old membership; stale handles cannot update reused turn IDs. Lookup retains agent, conversation, parent-thread, session and claimed predicates, then rechecks primary object identity after the durability wait. (src/sessions/conversation-turns.ts:128, be9686c20bdc)
  • Restart cleanup uses the existing owner: Both registries register close-and-restart resets through the shared singleton helper. Gateway shutdown invokes that drain after plugin cleanup; it settles waiters and clears the secondary index while retaining shared object identities. (src/gateway/server-close.ts:623, be9686c20bdc)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • joshavant: 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.

History

Review history (5 earlier review cycles)
  • reviewed 2026-08-21T12:32:07.005Z sha 648a5b2 :: found issues before merge. :: [P2] Preserve registration order for equal timestamps
  • reviewed 2026-08-22T14:30:47.685Z sha 648a5b2 :: found issues before merge. :: [P2] Retain registration order when timestamps tie
  • reviewed 2026-08-22T14:43:00.446Z sha 648a5b2 :: needs changes before merge. :: [P2] Preserve registration order when timestamps tie
  • reviewed August 24, 2026, 10:28 AM ET / 14:28 UTC sha unknown :: found issues before merge. :: [P2] Preserve registration order when timestamps tie
  • reviewed 2026-09-02T07:25:17.139Z sha 648a5b2 :: found issues before merge. :: [P2] Preserve registration order when timestamps tie

@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

The indexed reply lookup fixes the reported quadratic work at the pending-turn lifecycle owner. In a direct source-level run of 1,000 correlated replies, main visited 500,500 registry entries and the candidate visited zero; all replies matched correctly and both registries were empty after completion and restart. The measured claim/complete loop was 31.66 ms versus 2.47 ms on this run; the deterministic visit counts are the performance proof, not a general latency guarantee. Source imports were redirected only to isolated copies of the same normalization and singleton helpers for this harness.

Independent lifecycle review and fresh Codex autoreview found no actionable P0-P2 findings. The index is maintained during outbound-ID replacement and removed through the shared settle owner on completion, timeout, cancellation and abort. Canonical object checks preserve turn-ID reuse; released claims remain retryable. Agent, session, conversation and thread eligibility and transcript-durability waits remain unchanged.

ClawSweeper's equal-timestamp reverse-assignment finding and its two rank-up moves were checked against the sole production registrar. src/gateway/conversation-turn.ts calls registerPendingConversationTurn and immediately setOutboundMessageId(preparedMessageId) without an intervening await. It never reassigns that ID: a transport mismatch cancels the turn. Thus bucket insertion and registration order coincide in the actual flow. The proposed extra registration ordinal and reverse-assignment-only test are skipped because they preserve an unreachable internal state; the existing collision and replacement tests remain.

Best-fix verdict: the owner-level secondary index is the appropriate repair. A linear scan without sorting still visits every unrelated waiter; a cache or index in individual channels would duplicate lifecycle policy. Production +51/-17 (net +34), tests +145. The additional production state is required to index exact reply identities and clean it up without a global scan. No database/schema change is involved.

The old failed CI job was the portal retry-page test using a released ephemeral port (expected 502, observed 401). Main already fixes that race in 9177024 (#130920). The branch refresh will retain that correction before current-head validation.

@steipete steipete self-assigned this Sep 5, 2026
@steipete
steipete force-pushed the codex/fix-conversation-turn-reply-index branch from 648a5b2 to be9686c Compare September 5, 2026 02:59
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Refreshed onto main without changing the reviewed patch. All 83 focused tests and changed-file checks pass. The PR body now records the 1,000-reply failing/passing regression, cleanup proof, independent review, and the production-caller evidence resolving the equal-timestamp assignment concern. Current head: be9686c.

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 5, 2026
@steipete

steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor Author

The fresh review's remaining data-model flag does not apply to this change: JSON.stringify only constructs an in-memory Map key. pendingTurnsByOutboundId is a process-local singleton containing existing waiter objects; it has no file/SQLite writer or reader. No persisted representation, schema, migration, retention policy, or upgrade format changes.

Upgrade/restart compatibility follows the existing waiter lifecycle: process shutdown discards these registries, and the registered close/restart drain settles primary waiters and clears the secondary index. The 1,000-reply owner proof verified both maps empty after completion and after an explicit restart drain. The primary registry and durable conversation-delivery records keep their existing roles. No data migration is needed.

The rebased exact head be9686c20bdccf1e00042b85a492d68d8424db0e now has green required CI: https://github.com/openclaw/openclaw/actions/runs/33940626383. Local worker validation also passed all 83 focused tests and the complete changed-file gate. Native review artifacts validate with no findings.

@steipete
steipete merged commit 6b4e61b into main Sep 5, 2026
190 checks passed
@steipete
steipete deleted the codex/fix-conversation-turn-reply-index branch September 5, 2026 03:11
@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

maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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.

Conversation reply correlation scans the full pending-turn registry

2 participants