Skip to content

improve(database): compute PostgreSQL search snippets with one headline per row - #188951

Closed
etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:perf/pg-session-search-snippet-once
Closed

etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:perf/pg-session-search-snippet-once

Conversation

@etzelm

@etzelm etzelm commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

PostgreSQL session and memory keyword search spends about half of its snippet time computing the same headline twice for every returned row.

User Impact

User impact: sessions.search (and other PostgreSQL text-search snippets on version 2 indexes) builds each snippet with about half the database CPU, and the snippet text is unchanged.

Why This Change Was Made

Version 2 snippets re-slice the headline from the original text so displayed punctuation survives. The expression repeated the punctuation split three times and ts_headline twice per row, because strpos(...) and length(...) each embedded the same headline call. The snippet is now a scalar subquery that splits once and headlines once. OFFSET 0 keeps PostgreSQL from inlining the subqueries back into each reference; without it the plan still calls ts_headline twice (checked by mutation, below). Version 1 snippets and SQLite are unchanged.

Evidence

  • Output is byte-identical on real data. On a ported production store (PostgreSQL 17.11), the old and new expressions were compared on every transcript row the 12 benchmark search terms match in one agent (8,872 rows): 0 differences. The full captured sessions.search statements for all 12 terms return identical result sets (md5) before and after.
  • Snippet CPU is about 2.2x lower. Snippet-only microbench over those 8,872 rows, one statement per pass, old and new interleaved, 6 passes each: old 14.4 / 19.5 / 8.3 / 8.8 / 8.6 / 9.2 s, new 8.2 / 8.7 / 3.7 / 4.1 / 4.4 / 3.9 s. The per-pass ratio is 1.75-2.34 (median 2.2), or about 0.98 vs 0.45 ms per snippet once host load settled. The host was shared (load average 21-58), which is why it is reported as paired passes.
  • In context: for "postgres" (21 rows), the hits CTE finishes in about 2 ms and the rest of the statement is mostly snippets, so this is the main remaining per-query cost once the text index is used.
  • Test: node scripts/test-database-conformance.mjs --engine postgres --connection <dsn> -- src/infra/database-engine/postgres-text-search-schema.postgres.test.ts src/infra/database-engine/session-search-product.postgres.test.ts src/infra/database-engine/postgres-search.conformance.test.ts
    • Base plus the new test: 1 failed / 15 passed. expected [ 'ts_headline(', 'ts_headline(' ] to have a length of 1 but got 2.
    • With the change: 16/16 pass, including the existing punctuation-snippet product test.
    • Mutation (change without the OFFSET 0 fences): fails the same way (2 headlines), because PostgreSQL pulls the subqueries up.
  • oxfmt and oxlint are clean on both files.

Gap: gateway-level search latency on the shared host (load average 12-100 during the runs) was too noisy to attribute a latency number to this change alone. In the one interleaved round where base and this change ran at similar load (12-16), search SQL per call in pg_stat_statements dropped from 21.6 to 15.5 ms (concurrency 1), 21.1 to 15.2 ms (concurrency 8) and 21.5 to 17.6 ms (read mix). Separately, the Gateway currently runs sessions.search on a generic plan that skips the text index (see the linked issue). That dominates end-to-end search time until it is fixed, and this change applies on top of either plan.

…ne per row

- Version 2 text search snippets embedded the punctuation split three times and
  ts_headline twice per row (strpos and length each repeated the headline call).
- The snippet is now a scalar subquery: split once, headline once. OFFSET 0 keeps
  PostgreSQL from inlining the subqueries back into each reference.
- Output is unchanged; the test pins the snippet text and asserts one ts_headline
  and one split in the EXPLAIN VERBOSE plan.
@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-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-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 computes punctuation normalization and the PostgreSQL headline once per version 2 search snippet.

Example: Search for server.py in the existing deployment-note fixture.

  • Before: The snippet is "server.py landed; the API serves", with two embedded headline evaluations.
  • After: The same snippet is returned using one headline evaluation.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-consistent optimization with real-data and Gateway measurements, a reported red/green regression, and no identified defects; PostgreSQL CI shards were still running when inspected.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The contributor records real PostgreSQL 17.11 before/after snippet comparisons, captured sessions.search result equality, and Gateway pg_stat_statements measurements for the changed SQL path; these support reduced snippet work without claiming a reliable end-to-end latency improvement on the shared host.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: PostgreSQL search spends avoidable database CPU constructing each returned snippet.
Reason: The change deletes repeated work at the existing owner, preserves output and defaults, and has paired real-data measurements supporting its value.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused, useful PostgreSQL optimization that current main still needs; no actionable correctness or security defects were found.

Priority: P2
Reviewed head: c092871ae470cd52ead58af49f31d9146dffcf58

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared PostgreSQL search adapter converts admitted index fields and literal queries into SQL expressions consumed by transcript search and other text-search callers.

flowchart TD
A[Session search request] --> B[Scoped transcript search]
B --> C[Shared PostgreSQL search adapter]
C --> D[Normalize punctuation once]
D --> E[Compute headline once]
E --> F[Slice original text]
F --> G[Search results with snippets]
Loading

Technical review

Best possible solution:

Retain this shared-owner optimization and its focused regression while keeping the generic-plan repair separate.

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

Current-main source directly shows the duplicated headline expression, and the contributor reports a base-failing PostgreSQL plan regression; this review ran no target code.

Is this the best way to solve the issue?

The smallest complete fix is to reuse normalization and headline results inside the existing adapter while preserving original-text slicing; both OFFSET fences have a reported mutation check showing why they are necessary.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Version 2 PostgreSQL snippet construction keeps the original intent (338c811: Normalize punctuation for headline matching, then slice the corresponding original text so late matching passages retain displayed punctuation.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit bf46379 adds src/infra/database-engine/postgres-search.ts:83 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bf4637941b40; files: src/infra/database-engine/postgres-search.ts)

PR surface

Source 0, Tests +34. Total +34 across 2 files. Added test files: 0.

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

Labels

Label changes:

  • add P2: This reduces PostgreSQL CPU spent constructing search snippets while preserving search results; no outage or incorrect result is established.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This reduces PostgreSQL CPU spent constructing search snippets while preserving search results; no outage or incorrect result is established.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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.

Reviewed October 30, 2026, 10:10 PM ET / October 31, 2026, 02:10 UTC.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @etzelm for this optimization! Landed a credited replacement in #190309, preserving the snippet output and adding a PostgreSQL plan regression. Closing this as superseded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor 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. 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.

2 participants