Skip to content

fix: session search on PostgreSQL scans every transcript row instead of using the text index - #187909

Merged
obviyus merged 2 commits into
openclaw:mainfrom
etzelm:fix/pg-session-search-scope-prefix
Oct 29, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
etzelm:fix/pg-session-search-scope-prefix

Conversation

@etzelm

@etzelm etzelm commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #187908

What Problem This Solves

Default-agent session search on PostgreSQL can drive the join from every agent transcript row instead of using the selective full-text GIN index. The LEFT(session_key, N) expression has no useful column statistics, producing a poor scope estimate and thousands of primary-key lookups.

Why This Change Was Made

Use PostgreSQL's equivalent parameterized literal-prefix operator ^@ in the existing default-agent branch. It preserves literal underscores (dev_ops is not devxops) while exposing prefix selectivity to the planner. Explicit selections and other scopes retain their existing paths. No DDL, index, schema, migration, SDK, config or authorization change.

Original fix by @etzelm; contributor commits preserved. The namespace regression is consolidated into the existing scope case, with zero test-registration growth. Whole-PR delta: production +1/-1, tests +6/-0, docs +5/-0.

Evidence

Complete built main/candidate Gateways on Node 24.22.1 and real PostgreSQL 17.8 in secretless Docker. Production schema/indexes, 122 sessions and 9,604 indexed messages (8,000 belonging to the default agent), normal statistics, no planner forcing. Actual default-agent RPC SQL and bound parameters were captured server-side and replayed unchanged through EXPLAIN (ANALYZE, BUFFERS) twice per build.

Main performs 8,000 FTS primary-key loops; candidate uses a GIN bitmap scan of 12 text matches. SQL execution: main 13.062/9.363 ms, candidate 0.963/0.853 ms. Thirty warmed public RPC samples per independent run give p50 main 11.092/11.999 ms, candidate 3.687/4.328 ms (2.8–3.0× median improvement). Logging was disabled for timed RPCs. Complete result arrays are identical; the real underscore-agent RPC control returns only dev_ops, not devxops.

Formatting passed; selected PostgreSQL product suite 4/4. This proves the default RPC branch on this workload, not universal scope speedups, concurrency throughput or SQLite parity.

Exact-head measured Gateway/SQL evidence.

Merge danger

Two-way door: reverting restores the prior predicate without data changes or migrations. Blast radius is PostgreSQL default-agent transcript search planning; result filtering and literal namespace semantics remain unchanged. SQLite and explicitly selected session queries are not changed.

- Postgres scope filter left(session_key, N) = prefix has no planner
  statistics; the 0.5% default estimate drove a nested loop that
  evaluated the tsquery on every transcript row and skipped the GIN index
- session_key ^@ prefix is the same literal prefix test and has prefix
  selectivity, so the GIN match drives the join
- SQL per search 23-31 ms -> 4.7-16 ms on 7,956 rows; identical results
- sessions.search p50/p95/p99 103/187/253 -> 22/47/74 ms at concurrency 8
- add test: agent key prefix matches literally (dev_ops vs devxops)
@clawsweeper

clawsweeper Bot commented Oct 29, 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces PostgreSQL’s expression-based agent namespace filter with a parameterized literal-prefix operator.

Example: Search for "lighthouse migration" through the default-agent sessions.search RPC over 8,000 indexed main-agent messages.

  • Before: The supplied baseline performs 8,000 FTS primary-key lookups.
  • After: The candidate uses a GIN bitmap scan over 12 text matches and returns the same 10 authorized results.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, behavior-preserving repair with exact-head Gateway evidence and no actionable findings; broad CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): At dbfb4c9, obviyus exercised the public built-Gateway sessions.search RPC on real PostgreSQL 17.8 with production indexes and normal statistics; captured SQL plans show selective GIN access, repeated RPC medians improve 2.8–3.0×, full results remain identical, and the literal underscore control passes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL session searches can inspect every agent transcript row even when very few messages match.
Reason: Measured work reduction and lower public-RPC latency justify the minimal change while preserving designed search behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it makes a measured PostgreSQL search improvement with a minimal predicate replacement and no actionable defects; exact-head CI remains pending.

Priority: P2
Reviewed head: dbfb4c98ca6c24fd7593ce14af45abfe6a0c16f4

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway session search resolves the requested scope, dispatches transcript queries through the existing database worker, and returns ranked, bounded transcript excerpts.

flowchart LR
  A[Search RPC] --> B[Scope resolution]
  B --> C[Transcript worker]
  C --> D[Literal namespace predicate]
  D --> E[PostgreSQL text index]
  E --> F[Ranked bounded results]
Loading

Technical review

Best possible solution:

Retain the one-line predicate replacement and consolidated namespace coverage, then land through the normal exact-head CI gates.

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

The supplied built-Gateway baseline reproduces the excessive lookups through the actual default RPC, and fetched main retains the responsible predicate; no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete repair: change the existing query owner’s prefix primitive while preserving literal matching and every surrounding filter.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • PostgreSQL agent namespace filtering keeps the original intent (1e2d50c: The selected-engine cutover required PostgreSQL-compatible literal namespace filtering, including underscores in agent IDs.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source 0, Tests +6, Docs +5. Total +11 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 1 1 0
Tests 1 6 0 +6
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 12 1 +11

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #187908
Summary: This PR directly repairs the expression-based planner selectivity problem documented in the linked open issue.

Members:

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This improves PostgreSQL transcript-search latency on populated stores without changing results or introducing an urgent availability failure.
  • 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 execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-29T21:38:33.568Z sha 2c1e4d3 :: needs maintainer review before merge. :: none

Reviewed October 29, 2026, 6:26 PM ET / 22:26 UTC (Revision 2).

@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 29, 2026
@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Exact-head real PostgreSQL / built-Gateway proof

Candidate dbfb4c98ca6c24fd7593ce14af45abfe6a0c16f4; frozen main 7fb1e9cce6f80859918fb786d6d37d577717bc20. Full source/runtime builds in secretless Node 24.22.1 Docker; real PostgreSQL 17.8 (pgvector/pgvector:0.8.1-pg17) on arm64. The candidate was rebuilt in full after the final test/docs commit; its production predicate is unchanged from the contributor fix.

Workload and boundary: actual public built Gateway sessions.search RPC, with {query:"lighthouse migration",limit:25} and no scope, sessionKeys or explicit agent selector. Normal Gateway/session creation bootstraps the production agent schema/indexes. While Gateways were stopped, an offline SQL fixture populated 122 session windows and 9,604 indexed user/assistant messages: main 100×80 = 8,000, other 20×80 = 1,600, plus two messages each for dev_ops and devxops. Representative engineering transcript text, sparse matching terms, stable IDs/timestamps; normal generated FTS trigger and GIN index. ANALYZE ran on both corpora. Agent storage is PostgreSQL; unrelated shared state remains SQLite. No planner-forcing switches, new indexes, schema alterations or production instrumentation.

Actual default-RPC SQL plans

PostgreSQL auto_explain captured the actual RPC SQL and all bound parameters. The same query/parameters were then passed unchanged to EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) under the matching schema and read-only transaction. Not a simplified stand-in query.

                         main run 1   main run 2   candidate run 1   candidate run 2
FTS primary-key loops    8,000        8,000        no 8,000-loop scan no 8,000-loop scan
FTS GIN bitmap scan      absent       absent       1 loop / 12 rows   1 loop / 12 rows
SQL execution, ms        13.062       9.363        0.963              0.853
returned main hits       10           10           10                 10

Main's LEFT expression drives transcript primary-key lookups across every main-agent row; the parameterized literal ^@ predicate lets the selective text index drive the candidate join. Two of the twelve text matches belong to the other agent and remain excluded.

Repeated timed public RPCs

Each independent Gateway run used an authenticated persistent real RPC client, three warmups and 30 measured sequential searches. Plan logging was disabled for the measurement role (auto_explain.log_min_duration=-1); timings include actual Gateway/worker/network overhead, not CLI process startup.

Build Repetition RPC p50 ms RPC p95 ms
main 1 11.092 15.416
main 2 11.999 15.978
candidate 1 3.687 4.850
candidate 2 4.328 11.749

Observed default-branch median improvement: 2.8–3.0× on this corpus. The second candidate p95 shows ordinary tail noise; no claim that every request or every search scope is faster, no concurrency-throughput or SQLite-parity claim.

Correctness: complete result arrays (IDs, keys, roles, timestamps, snippets and scores) are identical across all four runs. Each run also invokes the real RPC with agentId:"dev_ops",query:"quay signal": exactly the two dev_ops results, never devxops; full control arrays are identical across runs. All measured calls retain the same ten-hit result set. Gateways stopped after proof; PostgreSQL/container/corpus retained for resumption.

Focused checks: formatting passed; the selected real-PostgreSQL product suite passed 4/4, including the underscore/lookalike case consolidated into its existing agent/session/role scope case. Registered-test growth 0. Contributor commits retained. Whole-PR delta versus merge base: production +1/-1, tests +6/-0, docs +5/-0. No DDL/index/schema/migration/SDK/config/auth changes in the PR.

@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Oct 29, 2026
@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 29, 2026
@obviyus
obviyus merged commit 6ba197f into openclaw:main Oct 29, 2026
136 of 138 checks passed
@obviyus

obviyus commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Landed in 6ba197f. Thanks @etzelm. Default-agent session search on PostgreSQL now uses its index.

@etzelm
etzelm deleted the fix/pg-session-search-scope-prefix branch October 29, 2026 23:30
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 30, 2026
…of using the text index (openclaw#187909)

fix(sessions): use the GIN index for the default-agent session search on PostgreSQL

On PostgreSQL, the default-agent session search filtered by agent prefix with LEFT(), which has no statistics, so the planner ran about 8,000 primary-key loops instead of using the existing GIN index. The filter now uses the equivalent parameterized ^@ literal prefix. No DDL, index, schema, migration, config or auth change, and underscores stay literal (dev_ops never matches devxops).

Evidence: built Gateway with real PostgreSQL 17.8 and a 9,604-message indexed corpus (8,000 default-agent messages), with the actual RPC SQL captured on the server. Main ran 8,000 primary-key loops in 13.1 and 9.4 ms; with this change a GIN bitmap scan found the 12 matches in 0.96 and 0.85 ms (twice each). Across 30 timed RPCs per run, the median dropped from about 11 to 12 ms to 3.7 to 4.3 ms, for this default branch only. Result arrays were identical, and the underscore control returned only dev_ops. Details: openclaw#187909 (comment).

Thanks @etzelm.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 5, 2026
Backport accepted fixes onto 2026.11.5-beta.2.

Base: bc061f9
Canonical source tree before commit: e6c0c39

These are adapted/squashed backports; do not claim each is an exact Git cherry-pick.
Source provenance (selected verified commits; other cohorts use their frozen patch/adoption manifests):

runtime-B:
b20a0cc fix(macos): connect with configured credentials despite stale app environment (#191468)
c4c0942 fix(update): failed updates from 10.7–10.9 crash in automatic migration recovery (#189713)
6aae408 fix(update): preserve recovery errors and async triage callbacks (#191495)
8910654 fix(macos): prevent first-launch Gateway failures after upgrades (#191436)
00b2ff4 fix: parent sessions miss child approvals with a custom session store (#189827)
c6142a8 fix: avoid copying managed plugin binaries during Gateway startup (#187865)
e72b356 fix(anthropic): avoid token profile collisions (#187875)
807075d fix(anthropic): set API workspace at login (#186976)
bafe92f fix(exec): preserve no-timeout results from macOS app nodes (#190729)
9b05a64 fix(imessage): use a PostgreSQL-safe recovery cursor key (#184919)
6ba197f fix: session search on PostgreSQL scans every transcript row instead of using the text index (#187909)
4f49aa5 fix(sessions): PostgreSQL session search scans every transcript row again after the 5th search on a connection (#188979)
de3936c fix(macos): Mac tab shows a blank or stale page when a load fails (#185432)
e977080 fix(macos): prevent duplicate voice sends and false sent feedback (#186271)

provider-compaction:
1b43c2e fix(compaction): preserve active request provenance (#180214)
7b0cfe3 fix(google): restore tool calls with Python keyword parameters (#191561)
9039ceb fix(ci): keep compaction attribution helpers internal
d6a1327 feat(google): use the Interactions API for Gemini Flash models (#189395)
fe0f8d1 fix(google): Gemini models ignore configured topP (#190695)

history:
c51d733 fix(sessions): stop expanding archive reads from exhausting memory (#190690)
3c8bd4d fix(sessions): page oversized earlier history instead of failing at 8 MiB (#188450)
b195f61 fix(sessions): page oversized transcript history in both directions (#188483)
b65482e fix(gateway): preserve older history across hidden message gaps (#188557)
3d4fc94 fix(sessions): avoid oversized listing and imported-history reads (#189284)
33e7baf fix(sessions): bound active accounting without blocking writers (#190182)
682ade7 fix: preserve chat history continuation metadata (#188612)

runtime-C:
7e005b0 fix(macos): keep secrets when a Gateway config save fails (#187734)
15cf738 fix(macos): keep Gateway auth when Tailscale exposure is turned off (#187664)
b53a06b perf(update): read candidate state inventory without copying the shared database (#187921)
970fc4e fix: restore CLI message sends with agent tool policies (#188058)
73ad731 fix: stop model fallback when session capability metadata changes (#179312)
32305db fix: subagent turns fail after session metadata changes (#183501)
d13bd0f fix(codex): include relay conversation instructions in trajectory (#189005)
e375530 fix: replies after a plugin reload from Control UI go to the session's last external chat (#190982)
9346376 fix: reasoning-only retry is refused by Anthropic as reasoning_extraction (#184434)

direct-auth-state:
1b15408 fix(models): keep the model list when one plugin-owned provider lacks a credential (#189014)
7d8dc60 fix: recover startup migration with retained worker index (#189023)

capacity:
41772e3 fix(worktrees): settle completed disk debt on refused postchecks (#188727)

command-once-189369:
8269137 fix(plugins): plugin commands that continue the agent run three times on native command turns (#189369)

pg-board-189564:
7232a8d fix(boards): publish widgets with PostgreSQL storage (#189564)

queued-edit-189869:
92b32ca fix: hold queued messages through inline edits (#189869)

Preserve source attribution from original commits. For a genuinely exact individual pick only, use the conventional (cherry picked from commit <sha>) line.
Full file-level provenance: coverage-manifest.json; reviewed patch hashes: artifact-registry.json.
No held136/native82 content adopted by this work. No release or full-candidate qualification claim.

Additional original-source identities (exact adapted hunk scope is in frozen artifacts):
release-guides-185258: 39c37e6 docs(release): define ledger-first hotfix routing (#185258)
UI-history: 10a6e4f fix(ui): scope provider-add discovery warning to its own provider (#188541), 3d7b4c4 fix(ui): never fail loading earlier chat history without a boundary (#188372)
obsolete-cache-188203: 90d82c2 fix: preserve completed reasoning and refill chat snapshots (#188203)
webhook-169778: b1f643f fix(startup): keep webhook decisions startup recorded for channels Doctor left pending (#169778)
schema-lease-188391: ba6cfcd fix(state): keep lease renewal independent of parent admission (#188391)
backfill-188976: c75a8a8 fix(gateway): stop session row backfill once the Gateway is closing (#188976)
canonical-disable-188846: 88b56ee fix(config): auto-enable reads and writes mixed-case plugin policy under the canonical id (#188846)
matrix-177272: 5a6d22c fix(matrix): stop seeding new thread sessions from the room transcript (#177272)
provider-hook-189059: 0588f51 fix(models): isolate every per-provider catalog failure (#189059)
unicode-189868: 87396e7 fix(oc-path): avoid reading and editing a different Unicode key (#189868)
replay-cohort: 2031044 fix(sessions): acknowledge committed input retries without duplicate turns (#188527), 9114431 fix: resume configured fallback after interrupted attempts (#188672)

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor docs Improvements or additions to documentation 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: XS 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.

sessions.search on PostgreSQL never uses the transcript GIN index (left() scope filter defeats the planner)

3 participants