Skip to content

Conversation

@omertuc
Copy link
Contributor

@omertuc omertuc commented Aug 20, 2025

Description

Trying to solve an issue similar to llamastack/llama-stack#3208

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

llamastack/llama-stack#3208

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

We're still testing in the process of testing it manually, we're not sure it helps solve our issue, but it also doesn't seem like it can cause much harm

Summary by CodeRabbit

  • Bug Fixes
    • Improved database connection stability by enabling connection pool pre-ping, reducing intermittent errors after idle periods across supported databases.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Enables SQLAlchemy connection pool pre-ping by adding pool_pre_ping: True to create_engine_kwargs within initialize_database(), affecting both SQLite and PostgreSQL engine creation. No other logic or public interfaces were changed.

Changes

Cohort / File(s) Summary
Database engine initialization
src/app/database.py
Add pool_pre_ping: True to create_engine kwargs used for engine creation across SQLite and PostgreSQL.

Sequence Diagram(s)

sequenceDiagram
    participant App as initialize_database()
    participant SA as SQLAlchemy Engine
    participant Pool as Connection Pool
    participant DB as Database

    App->>SA: create_engine(..., pool_pre_ping=True)
    note right of SA: Engine configured to pre-ping

    App->>Pool: acquire connection
    Pool->>DB: SELECT 1 (pre-ping)
    alt ping ok
        DB-->>Pool: ok
        Pool-->>App: live connection
    else ping fails
        DB-->>Pool: failure
        Pool->>DB: reconnect and retry
        Pool-->>App: fresh connection or raise
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~6 minutes

Poem

I twitch my ears at pings that sing,
A heartbeat check on every spring—
Connections hop, no stale surprise,
The pool pre-pings, with watchful eyes.
I thump, approve, then swiftly bring
A tunnel burrowed—healthy string! 🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/app/database.py (2)

110-113: Optional: limit pre_ping to networked DBs to avoid needless round-trips on SQLite

Pre-ping adds a round-trip per checkout. It’s typically unnecessary for local SQLite and can be reserved for Postgres (or other networked DBs). If you want to keep it simple, your current approach is fine; otherwise, consider this tweak.

Apply:

@@
-    create_engine_kwargs = {
-        "echo": echo,
-        "pool_pre_ping": True,
-    }
+    create_engine_kwargs = {
+        "echo": echo,
+    }
@@
-            engine = _create_postgres_engine(postgres_config, **create_engine_kwargs)
+            engine = _create_postgres_engine(
+                postgres_config,
+                pool_pre_ping=True,
+                **create_engine_kwargs,
+            )

Also applies to: 121-123


61-65: Optional: build the Postgres URL via SQLAlchemy’s URL.create to avoid escaping bugs

Manually composing the DSN risks breakage if usernames/passwords include reserved characters (:, @, /, %). Using URL.create handles proper quoting and keeps things robust.

Apply:

-    postgres_url = (
-        f"postgresql://{config.user}:{config.password}@"
-        f"{config.host}:{config.port}/{config.db}"
-        f"?sslmode={config.ssl_mode}&gssencmode={config.gss_encmode}"
-    )
+    postgres_url = URL.create(
+        "postgresql",
+        username=config.user,
+        password=config.password,
+        host=config.host,
+        port=config.port,
+        database=config.db,
+        query={"sslmode": config.ssl_mode, "gssencmode": config.gss_encmode},
+    )

Additionally add this import near your other SQLAlchemy imports:

from sqlalchemy.engine import URL
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 45eb299 and c59ea53.

📒 Files selected for processing (1)
  • src/app/database.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests
🔇 Additional comments (2)
src/app/database.py (2)

112-112: Pre-ping enabled on the pool — LGTM

Enabling pool_pre_ping is a solid, low-risk way to mitigate stale/disconnected connection errors (e.g., with PG/pgBouncer or idle timeout). This should improve resilience without altering call sites.


101-126: SQLAlchemy version pin and create_engine usage verified

  • pyproject.toml pins sqlalchemy>=2.0.42, which fully supports pool_pre_ping.
  • No other create_engine() call sites were found outside src/app/database.py.

All engines correctly go through initialize_database().

Copy link
Member

@maorfr maorfr left a comment

Choose a reason for hiding this comment

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

/lgtm

Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

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

LGTM, thank you

@tisnik tisnik merged commit c97daaf into lightspeed-core:main Aug 20, 2025
18 checks passed
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.

3 participants