Skip to content

Conversation

soekja
Copy link
Contributor

@soekja soekja commented Feb 17, 2025

Description

In it's current form, the entrypoint.sh script will run but fail with exit code 3 on the first docker compose up. Technically, running docker compose up a second time will not throw the same error and the application works fine. The new changes will improve the first time user experience and improve on some other aspects.

Summary of Changes:
1- entrypoint.sh to not fail with exit code 3 on first docker up.
2- Improved error and signal handling with set -e.
3- Improved database migration, verification and error handling. Avoids schema version mismatch and ensures db schema is always in sync with application code.
4- Added exec before Gunicorn commands to ensure proper signal handling.

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin

Summary by CodeRabbit

  • Chores
    • Improved error handling for smoother database migrations and startup.
    • Updated process management to ensure reliable application launch.
    • Optimized worker configuration and introduced a startup delay to guarantee database readiness.

…al handling, database stability in startup and migration

Signed-off-by: soekja <soekja@users.noreply.github.com>
Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

Walkthrough

The entrypoint.sh script has been updated to enhance error handling and control flow during database migrations and application startup. Key modifications include the introduction of set -e to ensure immediate exit on command failure, an active Alembic migration command with specific error handling, and a revised Gunicorn startup command using exec. A 2-second sleep delay has been added to ensure the database is ready before the application starts.

Changes

File Changes Summary
entrypoint.sh - Added set -e to exit on failure.
- Replaced commented Alembic migration with an active command that captures output and handles a "user already exists" error (prints a warning, otherwise exits on error).
- Modified Gunicorn startup to use exec for better process management.
- Introduced a 2-second sleep command to delay startup until the database is ready.

Sequence Diagram(s)

sequenceDiagram
    participant S as entrypoint.sh
    participant DB as Database
    participant APP as Application

    S->>DB: Execute migration command
    alt User already exists error
        DB-->>S: Return "user exists" error
        S->>S: Print warning, continue processing
    else Other errors
        DB-->>S: Return error
        S->>S: Exit with error message
    end
    S->>S: Sleep (2 seconds)
    S->>APP: Launch Gunicorn with exec (3 workers)
Loading

Poem

I'm a code-hopping rabbit, light on my feet,
Trailblazing through scripts with a rhythmic beat.
With set -e and graceful error play,
I guide migrations on their careful way.
Gunicorn awakens as I cheer in delight,
Hopping toward a future ever so bright! 🐰

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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)
entrypoint.sh (2)

21-22: Startup Delay to Ensure Database Readiness

The addition of a fixed sleep delay helps avoid race conditions by giving the database extra time to start up.

Suggestion: For enhanced robustness, consider replacing the fixed delay with a loop that continuously checks for database availability (e.g., using tools like nc or wait-for-it), especially if startup timing can vary.


32-34: Production Environment Startup Using exec

For environments other than development, the script appropriately starts Gunicorn using exec with production logging settings. This change supports proper signal forwarding and process management.

Note: The worker count has been reduced to 1. Please verify that this meets your anticipated production load or that horizontal scaling is adequately configured.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e4fd6a1 and 3072ab6.

📒 Files selected for processing (1)
  • entrypoint.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: lint (ubuntu-latest, 3.11.x)
  • GitHub Check: lint (ubuntu-latest, 3.10.x)
  • GitHub Check: Build Cognee Backend Docker App Image
  • GitHub Check: docker-compose-test
🔇 Additional comments (3)
entrypoint.sh (3)

3-3: Immediate Exit on Error with set -e

Adding set -e ensures the script exits as soon as any command fails, which is a best practice for robust shell scripting.


7-17: Enhanced Alembic Migration Error Handling

The migration block now captures the output from the Alembic upgrade and conditionally handles known error messages (e.g., a default user already exists). This design prevents the script from exiting on expected non-critical errors while ensuring unexpected failures are caught and reported.

Note: Since the error-checking depends on specific substrings, ensure these strings remain consistent with any future changes in the migration tool's output.


25-31: Dev Mode: Conditional Startup with Proper Signal Handling

This section correctly distinguishes between debug and non-debug modes in a development environment. Using exec to start the Python process (with or without debugpy) ensures that the Gunicorn process directly receives signals, which is essential for Docker container management.

# Run Alembic migrations with proper error handling
echo "Running database migrations..."
MIGRATION_OUTPUT=$(poetry run alembic upgrade head 2>&1) || {
if [[ $MIGRATION_OUTPUT == *"UserAlreadyExists"* ]] || [[ $MIGRATION_OUTPUT == *"User default_user@example.com already exists"* ]]; then
Copy link
Member

Choose a reason for hiding this comment

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

Can you put a comment describing the reasoning behind this check please? So it doesn't confuse us in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes I will make the updates to have the comments.

entrypoint.sh Outdated
if [ "$ENVIRONMENT" = "dev" ]; then
if [ "$DEBUG" = true ]; then
echo "Waiting for the debugger to attach..."
exec python -m debugpy --wait-for-client --listen 0.0.0.0:5678 -m gunicorn -w 1 -k uvicorn.workers.UvicornWorker -t 30000 --bind=0.0.0.0:8000 --log-level debug --reload cognee.api.client:app
Copy link
Member

Choose a reason for hiding this comment

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

Why do we decrease the number of workers to 1?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're right it should be set to 3 workers like the previous script.

@borisarzentar borisarzentar changed the title entrypoint.sh to not fail on first docker up, improved handling of migrations, signals and errors. fix: entrypoint.sh to not fail on first docker up, improved handling of migrations, signals and errors. Feb 19, 2025
Vasilije1990 and others added 2 commits February 20, 2025 15:36
…lreadyExists check

Signed-off-by: soekja <soekja@users.noreply.github.com>
@soekja
Copy link
Contributor Author

soekja commented Feb 20, 2025

Updated workers count and comments for UserAlreadyExists check as requested @borisarzentar

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)
entrypoint.sh (2)

3-3: Use of set -e for Immediate Exit on Errors
Introducing set -e is a good practice that ensures the script exits immediately if any command fails. As a further improvement, you might consider adding set -o pipefail to catch errors in pipelines as well.


29-30: Fixed Startup Delay for Database Readiness
Adding a 2-second sleep is a pragmatic way to allow the database time to become ready. In the long run, you might consider implementing a loop with a timeout that actively checks database connectivity, which would offer more robustness in varying environments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7b953 and 92eeebe.

📒 Files selected for processing (1)
  • entrypoint.sh (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (23)
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_eval_framework_test / test
  • GitHub Check: test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: run_simple_example_test / test
  • GitHub Check: run_dynamic_steps_example_test / test
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-15
  • GitHub Check: run_notebook_test / test
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-13
  • GitHub Check: Test on macos-13
  • GitHub Check: run_multimedia_example_test / test
  • GitHub Check: run_networkx_metrics_test / test
  • GitHub Check: test
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: windows-latest
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: Test on ubuntu-22.04
  • GitHub Check: test
  • GitHub Check: docker-compose-test
  • GitHub Check: Build Cognee Backend Docker App Image
🔇 Additional comments (3)
entrypoint.sh (3)

7-16: Detailed Documentation for Migration Error Handling
The added comments explaining the rationale behind ignoring non-critical "UserAlreadyExists" errors are very clear. This aligns well with previous feedback requesting additional context.


16-25: Robust Handling of Alembic Migration Errors
Capturing the migration output and conditionally handling known non-critical errors (like a duplicate user) ensures that unexpected migration failures are properly surfaced. The logic is sound and helps prevent false negatives during startup.


32-42: Enhanced Gunicorn Startup and Signal Handling
Switching to using exec for launching Gunicorn improves signal handling by replacing the shell process. The conditional logic distinguishes between development (with optional debug mode and live reloading) and production environments effectively. Ensure that production deployments do not inadvertently include development-only flags like --reload.

@Vasilije1990 Vasilije1990 merged commit fd3b15f into topoteretes:dev Feb 21, 2025
9 of 32 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