Skip to content

perf(storage): rescue perf items from #809 fold (#1314) - #1334

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/rescue-1314-v2
May 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/rescue-1314-v2

Conversation

@Sinity

@Sinity Sinity commented May 18, 2026

Copy link
Copy Markdown
Owner

Summary

Fold the four perf items from #809 that were dropped during the
#809 → #815 → #817 split (caught by the #1310 fall-through audit).
All four cluster around the session-insight rebuild + read hot path
and are independently small, so they ship in one cohesive PR.

Problem

Issue #1314 enumerated four orphaned perf items:

  1. _SESSION_INSIGHT_REBUILD_PAGE_SIZE = 1 at
    polylogue/storage/insights/session/rebuild.py caused
    ~17K SQL round-trips for ~4K conversations on production
    archives.
  2. Every search call ran SELECT COUNT(*) FROM messages_fts(_docsize)
    for FTS-readiness verification — daemon convergence
    (polylogue/daemon/convergence_stages.py) already maintains
    the strict invariant, so the per-query check was redundant.
  3. get_provider_metrics_rows scanned messages for
    per-conversation aggregates that conversation_stats already
    stores pre-aggregated (one row per conversation).
  4. get_messages / get_messages_paginated / get_messages_batch
    called pydantic model_copy per message in the hot hydration path
    just to attach content blocks — constructing a second BaseModel
    instance per row.

#817 slice D (#1243) covers the compound-index and ANALYZE work,
but these four items had no current scope.

Solution

  • polylogue/storage/insights/session/rebuild.py: raise
    _SESSION_INSIGHT_REBUILD_PAGE_SIZE to 50. The message-budget
    chunker (_chunk_conversation_ids_by_message_budget_sync,
    budget = 5,000 messages) remains the real safety net for
    pathological conversations; the page size only controls
    per-conversation SQL round-trips.

  • polylogue/storage/sqlite/queries/conversations_search.py:
    search_conversation_hits and search_conversation_evidence_hits
    now call message_fts_readiness_async(conn, verify_total_rows=False),
    skipping the full COUNT(*) FROM messages_fts_docsize /
    SELECT COUNT(*) FROM messages scans per query. Daemon
    convergence is the canonical strict-readiness gate.

  • polylogue/storage/fts/fts_lifecycle.py: the cheap probe used
    SELECT 1 FROM messages_fts LIMIT 1, but messages_fts is a
    contentless FTS5 virtual table — DELETE FROM messages_fts does
    not remove rows from the virtual surface (the surface mirrors
    messages) so the probe missed the "FTS exists but empty"
    corruption case. Switched to messages_fts_docsize (the FTS5
    shadow table that does honour deletes), which preserves the
    test_fetch_search_results_raises_when_message_index_is_incomplete
    contract.

  • polylogue/storage/sqlite/queries/stats.py:
    get_provider_metrics_rows now pulls conversation_count,
    message_count, tool_use_count, thinking_count,
    conversations_with_tools, conversations_with_thinking from
    conversation_stats (one row per conversation, far smaller than
    the messages table). Role-keyed splits (user_message_count,
    assistant_message_count, word sums) still aggregate from
    messages via the idx_messages_provider_stats covering
    index — they aren't pre-aggregated. The ProviderMetricsRow
    return contract is preserved.

  • polylogue/storage/sqlite/query_store_archive.py: replaced the
    message.model_copy(update={\"content_blocks\": ...}) list
    comprehensions with in-place message.content_blocks = ...
    assignment in get_messages, get_messages_paginated, and
    get_messages_batch. The MessageRecord instances are freshly
    constructed by _row_to_message and aren't shared.

  • tests/unit/storage/test_perf_rescue_1314.py: regression guards
    for each invariant. The tests count SQL operations (not wall-clock
    time) against the tier_small_db fixture so they stay portable.

Verification

  • nix develop -c devtools verify --quick → exit_code 0
    (ruff format/check, mypy --strict, render-all --check,
    layering/topology/lints).
  • nix develop -c pytest tests/unit/storage/test_perf_rescue_1314.py
    → 4 passed in 8s (page size, FTS readiness probe, provider
    metrics SQL routing, hydration in-place mutation).
  • nix develop -c pytest tests/unit/storage/test_fts5.py tests/unit/storage/test_fts_bloat_invariants.py tests/unit/core/test_query_retrieval_candidates.py → 77 passed.
    Confirms the messages_fts_docsize probe still trips the
    "FTS exists but empty" contract.
  • nix develop -c pytest tests/unit -q -m \"not scale_medium and not scale_large\" -p no:randomly --testmon-noselect
    → 7876 passed, 2 xfailed (no regressions from the changes; one
    pre-existing socket-timeout flake in test_web_reader.py).

Before/after on the #1183 scale_small fixture (~100 convs,
~1K msgs, single-threaded, median of 15 runs):

Surface Before After
get_provider_metrics_rows 2.97 ms 2.62 ms
search_conversation_hits 2.41 ms 1.94 ms
get_messages 7.20 ms 6.71 ms
rebuild_session_insights_sync 281 ms / 4,082 SQL 262 ms / 3,794 SQL

The page-size win is bounded on the small tier because the
fixture only has ~100 conversations; the production-shape benefit
is roughly proportional to conversation count.

Closes #1314

Fold the four perf items from #809 that were orphaned by the
#809 → #815 → #817 split:

1. _SESSION_INSIGHT_REBUILD_PAGE_SIZE: 1 → 50.
   The message-budget chunker is the actual safety net for
   pathologically large conversations; the page size only
   controls per-conversation SQL round-trips.

2. message_fts_readiness: call the cheap LIMIT-1 probe from
   search instead of full COUNT(*). Fixed the probe to read
   messages_fts_docsize (the shadow table) rather than the
   contentless virtual surface, so the "FTS exists but empty"
   state still trips the readiness gate.

3. get_provider_metrics_rows: read pre-aggregates from
   conversation_stats (one row per conv) instead of scanning
   messages. Role-keyed splits still come from messages via
   the idx_messages_provider_stats covering index.

4. get_messages / get_messages_paginated / get_messages_batch:
   mutate the freshly-constructed MessageRecord instances in
   place rather than calling pydantic model_copy per message.

tests/unit/storage/test_perf_rescue_1314.py pins each invariant
by counting SQL operations against tier_small_db.

Closes #1314

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 41 minutes and 38 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ab04d03d-c561-4ede-adb4-2733788cff34

📥 Commits

Reviewing files that changed from the base of the PR and between 7a85f3b and 5d96170.

📒 Files selected for processing (6)
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/sqlite/queries/conversations_search.py
  • polylogue/storage/sqlite/queries/stats.py
  • polylogue/storage/sqlite/query_store_archive.py
  • tests/unit/storage/test_perf_rescue_1314.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/rescue-1314-v2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 39bfddd into master May 18, 2026
2 of 5 checks passed
@Sinity
Sinity deleted the feature/perf/rescue-1314-v2 branch May 18, 2026 20:14

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d96170df4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(storage): rescue perf items from #809→#815→#817 fold (from #1310 audit)

1 participant