Skip to content

fix(sessions): PostgreSQL session search scans every transcript row again after the 5th search on a connection - #188979

Merged
obviyus merged 2 commits into
openclaw:mainfrom
etzelm:fix/pg-session-search-generic-plan
Oct 31, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
etzelm:fix/pg-session-search-generic-plan

Conversation

@etzelm

@etzelm etzelm commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #188954

What Problem This Solves

Repeated PostgreSQL sessions.search calls can stop using the text index when the reused prepared statement switches from custom to generic plans after five executions. The query then probes every transcript row belonging to the agent and applies the text match as a filter.

User Impact

Selective transcript searches retain the text-index plan in steady state without changing returned results. In the measured 6,000-row workload, generic-plan buffer accesses fall from 19,108 to 116 per search, a 99.39% reduction. This is workload-specific query work, not a fleet latency guarantee.

Why This Change Was Made

The existing PostgreSQL agent-prefix predicate now uses Kysely's quoted sql.lit(agentPrefix). The generic plan can retain the prefix selectivity estimate instead of estimating an unknown parameter. Other search inputs remain parameterized, underscores keep their literal meaning, and SQLite keeps its unchanged GLOB branch.

The existing prepared-statement cache remains bounded at 256 entries; this introduces no new cache, schema, configuration, server-wide plan policy or API. It does not force custom plans. The contributor's original fix and commit are retained.

Evidence

Independent built-Gateway PostgreSQL plans, repeated RPC measurements and SQLite controls.

  • Complete main 2919a0dba8d80d3d73ddf8620e2d5a8f2e1271ca and exact candidate 8341389b6a4048c3089f05954f0ab978341557bd, independently built in secretless Linux arm64 Docker, Node 24.22.1, real PostgreSQL 17.11.
  • Each independent database receives 300 sessions × 20 messages through a real Gateway plugin using public session/transcript SDK operations; a fixed rare term matches one row.
  • Two main and two candidate runs each execute 12 real sessions.search RPCs. All four naturally switch to generic plans on call 6 under unchanged plan_cache_mode=auto, with the same PostgreSQL backend retained within each run.
  • Both main runs lose the GIN text index and make 6,000 transcript PK probes from call 6 onward. Both candidate runs retain the GIN path and selective work throughout.
  • Actual server auto_explain ANALYZE/BUFFERS plans agree with independent per-call pg_stat_statements buffer deltas on all 48 calls. No planner mode or search implementation is mocked.
  • All PostgreSQL result rows are exactly identical. Built main/candidate SQLite controls each repeat the same 12 RPC searches against the same 6,000-row fixture and return identical SQLite results. Cross-engine identity, timestamp and snippet also match; relevance scores remain engine-local.
  • 38 existing tests passed across five files: 23 PostgreSQL search/projection/schema tests and 15 SQLite transcript-search tests. Scoped formatting passed.

Final introduced delta against the merge base: production +1/-1, docs +5/-0, tests +0/-0, no test-budget allocation. The added synthetic plan test was removed to meet the assigned zero-growth ceiling; existing consumer tests are unchanged. Simplification keeps the fix at the query owner with no extra helper or global policy.

Merge Danger

Two-way door: reverting restores the parameterized prefix and former plan behavior; no persistent migration or schema change is involved. Blast radius is PostgreSQL transcript searches using the agent-prefix scope. Kysely quotes the literal, while other inputs remain bound. SQLite behavior, result filtering/ranking and global planner policy are unchanged.

- Inline the agent prefix in the PostgreSQL `session_key ^@` scope filter
  as a quoted literal, so the reused prepared statement's generic plan keeps
  the starts_with estimate.
- Without it, after 5 executions PostgreSQL picks a generic plan that
  estimates a handful of windows and filters every transcript row of the
  agent with the tsquery instead of using session_transcript_fts_search_gin.
- Add a PostgreSQL product test that runs EXPLAIN (GENERIC_PLAN) on the
  compiled search statement and requires the text index.

Fixes openclaw#188954
@clawsweeper

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

clawsweeper Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR compiles the PostgreSQL agent-prefix filter as a quoted SQL literal so generic prepared plans retain its selectivity estimate.

Example: Search for plannerneedle 12 times against 6,000 transcript rows on a reused PostgreSQL connection.

  • Before: From call 6, the measured baseline makes 6,000 transcript primary-key probes and accesses 19,108 buffers per search.
  • After: The candidate retains the GIN text-index path, makes one primary-key probe, and accesses 116 buffers while returning identical results.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A minimal owner-local repair with exact-head shipped-entry-point proof, unchanged result semantics, and no actionable findings; required CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Exact head 8341389 was exercised through independently built Gateways and real sessions.search RPCs on PostgreSQL 17.11: generic plans retained the GIN path after call 5, buffer work fell from 19,108 to 116, results matched the baseline, and SQLite controls matched. Evidence: #188979 (comment).
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Repeated PostgreSQL session searches become slower and consume substantially more database work after a connection selects a generic plan.
Reason: The measured regression has a narrow repair that restores the existing search-performance intent while preserving results and scope.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a focused, proven repair for a PostgreSQL search regression still present on current main; no actionable defects were found, and required CI remains pending.

Priority: P2
Reviewed head: 8341389b6a4048c3089f05954f0ab978341557bd

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway sessions.search requests reach the transcript-search worker and query owner, which scopes indexed messages by agent or selected sessions and returns ranked snippets from PostgreSQL or SQLite.

flowchart LR
  A[Gateway search RPC] --> B[Session scope and visibility]
  B --> C[Transcript search worker]
  C --> D[Query owner]
  D --> E[PostgreSQL prepared statement]
  D --> F[SQLite search]
  E --> G[Ranked transcript hits]
  F --> G
Loading

Technical review

Best possible solution:

Merge the existing query-local literal repair once required exact-head CI passes.

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

Current main retains the parameterized prefix and named-statement reuse that enable the failure; obviyus supplies repeated built-Gateway baseline reproductions, which were inspected but not rerun during this read-only review.

Is this the best way to solve the issue?

The one-expression repair preserves prefix semantics and statement reuse at the existing query owner without introducing global planner policy, configuration, or additional machinery.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • PostgreSQL agent-prefix predicate keeps the original intent (6ba197f: Use the planner-selective starts-with operator while keeping underscores literal; this PR preserves that intent when prepared statements use generic plans.)
  • PostgreSQL operator-guide search section keeps the original intent (1e78ee6: Provide source-backed PostgreSQL operating guidance; the addition describes the query-local planning behavior without changing the documented support boundary.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1e2d50c adds src/config/sessions/session-transcript-search.ts:200 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1e2d50c66324; files: src/config/sessions/session-transcript-search.ts)

PR surface

Source 0, Docs +5. Total +5 across 2 files. Added test files: 0.

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

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #188954
Summary: This PR repairs the generic-plan selectivity failure tracked by the linked issue; the open snippet optimization addresses separate work.

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: Repeated PostgreSQL transcript searches can perform excessive database work while still returning correct results.
  • 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-31T02:50:12.164Z sha 4132c8d :: needs maintainer review before merge. :: none

Reviewed October 31, 2026, 12:04 AM ET / 04:04 UTC (Revision 2).

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XS and removed size: S labels Oct 31, 2026
@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Independent built-Gateway proof on exact head 8341389b6a4048c3089f05954f0ab978341557bd, compared with complete main 2919a0dba8d80d3d73ddf8620e2d5a8f2e1271ca.

Real workload and plan observation

Secretless Linux arm64 Docker, Node 24.22.1, PostgreSQL 17.11 (pgvector/pgvector:pg17, image digest sha256:ac08538c6f8b9904c33c8224c5e5706dbe760aca29db1d096972b4052c22a75d). Each run uses an independent database/role, explicit Gateway profile and isolated state/config paths. Both sources were independently built; the final candidate archive was rebuilt after the zero-test-growth/doc commit.

A task-owned Gateway plugin seeds 300 sessions × 20 transcript messages = 6,000 rows through the public session/transcript SDK. Exactly one message contains plannerneedle; all identities and timestamps are fixed across runs. After clean seed shutdown, PostgreSQL tables are analyzed, then the shipped openclaw.mjs ... gateway run starts again and serves 12 sequential real sessions.search RPC calls over one authenticated Gateway connection:

{"query":"plannerneedle","limit":10}

No search callback, SQL execution, prepared-statement cache or planner decision is mocked. plan_cache_mode stays auto; neither force-generic nor force-custom mode is used. Server-native auto_explain captures actual ANALYZE/BUFFERS JSON plans, while independent pg_stat_statements before/after snapshots measure each call. Those two buffer measurements agree on all 48 PostgreSQL searches. Each run's 12 statements execute on the same PostgreSQL backend PID.

Observed plan switch and buffer counts

Run Call 1 buffers Calls 2–5, each Calls 6–12, each GIN text index after switch Dominant transcript PK-probe loops after switch
Main 1 141 116 19,108 Absent 6,000
Main 2 141 116 19,108 Absent 6,000
Candidate 1 141 116 116 Present 1
Candidate 2 141 116 116 Present 1

In every run, the first five actual plans contain bound values; from call 6 onward, the server renders generic parameter references. Thus the candidate also really uses generic plans—it does not avoid the regression by forcing custom plans or opening new connections.

Both main runs regress at call 6: the plan walks every transcript mapping and probes session_transcript_fts_pkey 6,000 times, applying the tsquery as a filter rather than using session_transcript_fts_search_gin. This is a full logical transcript scan through PK probes, not a claim of a literal sequential scan on the FTS table. The candidate keeps the GIN path in all 12 executions. Steady-state buffer accesses fall 99.39%, from 19,108 to 116, in both comparisons. These are logical buffer accesses, not physical disk bytes or a fleet latency SLA.

Results and SQLite control

All 48 PostgreSQL RPC calls return exactly identical result rows, including identity, timestamp, snippet and score:

{"sessionKey":"agent:main:planner-0","sessionId":"00000000-0000-4000-8000-000000000000","messageId":"planner-0-0","role":"user","timestamp":1793418190039,"snippet":"plannerneedle","score":0.1}

The built-main and built-candidate SQLite controls each seed the same 6,000-row workload and run the same 12 real RPC searches. Their result rows are identical to one another. Cross-engine identity/timestamp/snippet also match; SQLite and PostgreSQL relevance scores remain engine-local, as documented, and are not asserted equal across engines.

All six Gateway runs pass health and stop without forced termination. 38 existing tests pass across five files: four PostgreSQL search/projection/schema consumers (23 tests) and SQLite transcript search (15 tests). Scoped formatting passes.

Repair boundary

The contributor's original query-local sql.lit(agentPrefix) fix is retained. Final introduced delta: production +1/-1, docs +5/-0, tests +0/-0, no test-budget allocation. The new synthetic plan test was removed to meet the assigned zero-growth ceiling; all pre-existing consumer assertions remain. Simplification adds no helper, cache, schema, configuration knob or server-wide plan policy. The text value is quoted by Kysely, not interpolated through raw SQL.

@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 31, 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 31, 2026
@obviyus
obviyus merged commit 4f49aa5 into openclaw:main Oct 31, 2026
141 of 145 checks passed
@obviyus

obviyus commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Landed in 4f49aa5. Thanks @etzelm. PostgreSQL session search now stays fast after repeated calls.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 1, 2026
…gain after the 5th search on a connection (openclaw#188979)

fix(postgres): keep session search index-selective after PostgreSQL switches to a generic plan

Fixes openclaw#188954.

PostgreSQL switches a reused prepared statement to a generic plan after a few executions. For `sessions.search` that generic plan lost the selectivity of the agent prefix filter, so from about the sixth call every search probed all transcripts by primary key. The agent prefix is now a query-local literal, so the planner keeps using the GIN index. There is no schema or global plan-policy change, and results are unchanged.

Evidence: real PostgreSQL 17.11 with built Gateways, 6,000 transcripts and 12 `sessions.search` calls per run. In both main runs the plan turned generic at call 6 and regressed to 6,000 primary-key probes and 19,108 buffers per call. In both candidate runs the plan also turned generic but kept the GIN index at 116 buffers per call, 99.4% less buffer work. Server plans and statement counters agreed on all 48 PostgreSQL calls, and results were identical. SQLite results were identical on both refs. Details: openclaw#188979 (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

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: 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.

[Bug]: sessions.search on PostgreSQL falls back to scanning every transcript row after the 5th search on a connection (prepared-statement generic plan)

2 participants