Skip to content

feat: parameterize ports/pod, fix valkey healthcheck, address all review comments#252

Closed
sheepdestroyer wants to merge 24 commits into
masterfrom
chore/learn-deployment-guidelines
Closed

feat: parameterize ports/pod, fix valkey healthcheck, address all review comments#252
sheepdestroyer wants to merge 24 commits into
masterfrom
chore/learn-deployment-guidelines

Conversation

@sheepdestroyer

@sheepdestroyer sheepdestroyer commented Jul 11, 2026

Copy link
Copy Markdown
Owner

Summary

Parameterizes all ports and pod name for parallel prod/dev deployments, fixes the Valkey restart loop caused by BusyBox nc -z incompatibility, and addresses all review comments from PRs #248, #249, #250, and #251.

Changes

Port & pod parameterization

  • All ports configurable via .env / .env.dev with +10 offset for dev
  • POD_NAME env var replaces hardcoded agent-router-pod throughout
  • ROUTER_IMAGE env var replaces hardcoded ghcr.io/sheepdestroyer/llm-routing:latest
  • DATA_ROOT defaults to WORKDIR/data, volume dirs created under it
  • deploy_fresh_pod() helper DRYs the repeated generate→render→deploy→verify sequence

Valkey healthcheck fix

  • Switched from tcpSocket probes to exec valkey-cli ping (with -p port)
  • Switched from valkey:9.1.0-alpine to valkey:9.1.0 (non-alpine has no broken nc -z)
  • Root cause: podman play kube converts tcpSocket to nc -z -v localhost <port>, BusyBox nc lacks -z, healthcheck always fails, HealthcheckOnFailureAction=restart causes infinite loop

Review fixes (all rounds)

  • litellm/entrypoint.py: restore quote stripping before setdefault, safe int parsing for POSTGRES_PORT
  • router/main.py: extract _valkey_port() helper (returns int, safe parsing), replace hardcoded :3001 with LANGFUSE_WEB_PORT, use LLAMA_SERVER_URL for health check
  • start-stack.sh: placeholder validation in both render_litellm_config and render_router_config, chmod 644 on rendered configs, remove undocumented --pull-latest alias, fix if/elif/else chain in first-deploy path
  • scripts/backup.sh: use POD_NAME and POSTGRES_PORT from .env, source DEV_ENV_FILE overlay
  • pod.yaml: remove redundant PORT env var (duplicate of LITELLM_PORT)
  • router/tests/test_get_redis.py: update test for _valkey_port() safe int parsing, add test_valkey_port_invalid_fallback
  • scripts/dev-setup.sh: new venv setup script for local test runs
  • .gitignore: add .venv/

Verified

  • 196 tests passed, 0 failed
  • valkey-cache: healthy, 0 SIGTERMs
  • valkey-lf: healthy, 0 SIGTERMs
  • Chat completions: 200 OK
  • Langfuse: 0 ECONNREFUSED

Summary by Sourcery

Parameterize ports, pod name, and router image for flexible prod/dev deployments, fix Valkey health checks, and update configs, scripts, and tests to align with the new runtime settings.

Bug Fixes:

  • Replace Valkey tcpSocket probes with exec-based valkey-cli ping and switch to the non-alpine Valkey image to prevent healthcheck-induced restart loops.
  • Ensure ClickHouse and PostgreSQL probes and clients use the configured ports, avoiding mismatches between containers and health checks.
  • Fix get_redis behavior to safely parse Valkey port, log invalid values, and correctly handle initialization failures.

Enhancements:

  • Make all service ports, pod name, router image, and data root configurable via environment variables, including a dev overlay and dynamic local base URL.
  • Introduce rendered LiteLLM and router configs, ClickHouse port override config, and a deploy_fresh_pod helper to standardize pod creation and health verification.
  • Update pod definition to use parameterized ports and volumes, derive proxy URLs from PUBLIC_BASE_URL, and wire services to the new config artifacts instead of source directories.
  • Improve LiteLLM entrypoint and router logic to respect POSTGRES_PORT, LITELLM_PORT, LANGFUSE_WEB_PORT, and dynamic Valkey cache ports, including dashboard and proxy paths.
  • Adjust backup script to read POD_NAME and POSTGRES_PORT from environment and support dev overlays.

Build:

  • Add a --pull mode to start-stack.sh, support both pulled and locally built router images via ROUTER_IMAGE, and correct first-deploy image selection logic.

Deployment:

  • Refactor start-stack.sh to use POD_NAME everywhere, clean up zombie ports based on configured values, and centralize pod deployment via deploy_fresh_pod.
  • Adjust MinIO setup to honor MINIO_S3_PORT and POD_NAME, and add ClickHouse port override volume and config directory under DATA_ROOT.
  • Add start-dev.sh and .env.dev to support parallel dev deployments on separate ports and data directories.

Tests:

  • Extend router tests to cover _valkey_port() fallback behavior and verify logging on invalid port values.

Chores:

  • Update .gitignore to ignore local virtual environment directories.

boy and others added 22 commits July 11, 2026 12:18
…yments

Replaces all hardcoded port values and the pod name in pod.yaml,
start-stack.sh, litellm/config.yaml and litellm/entrypoint.py with
environment-variable-driven placeholders. A single pod.yaml now serves
both the production agent-router-pod and the development dev-router-pod.

Changes:
- pod.yaml: rewrite with *_PLACEHOLDER vars for pod name, all 13 service
  ports, and DATA_ROOT; add clickhouse-port-config volume; litellm-config
  volume now points to DATA_ROOT/litellm-rendered (rendered copy)
- start-stack.sh: load optional DEV_ENV_FILE overlay; resolve port/name
  defaults after env sourcing; add generate_clickhouse_config() and
  render_litellm_config() helpers; parameterize all agent-router-pod refs
  and hardcoded ports throughout cleanup, health-check, and minio helpers
- litellm/config.yaml: replace port 6379 / 5000 with *_PLACEHOLDER vars
  (rendered at deploy time via render_litellm_config)
- litellm/entrypoint.py: read POSTGRES_PORT / LITELLM_PORT from env
  instead of hardcoded 5432 / 4000; use setdefault to not clobber
  container-injected env vars
- .env: append production port defaults (POD_NAME, ROUTER_PORT, ...)
- .env.dev: new dev overlay (POD_NAME=dev-router-pod, +10 port offsets,
  dev.vendeuvre.lan URLs)
- start-dev.sh: thin wrapper that sets DEV_ENV_FILE + DATA_ROOT then
  delegates to start-stack.sh
- .gitignore: exclude dev-data/ (dev-stack runtime volumes)
…non-alpine valkey image

Root cause: podman play kube converts tcpSocket liveness probes into
'nc -z -v localhost <port> || exit 1' healthchecks. Alpine's BusyBox nc
does not support -z, so the healthcheck always fails. With
HealthcheckOnFailureAction=restart, this causes an infinite SIGTERM
restart loop (~every 30s).

Changes:
- valkey-cache: tcpSocket -> exec valkey-cli ping (liveness + readiness)
- valkey-lf: tcpSocket -> exec valkey-cli -a <pass> ping (liveness)
- Image: valkey:9.1.0-alpine -> valkey:9.1.0 (non-alpine has no nc,
  so no broken built-in healthcheck to conflict with)

Verified in dev: 0 SIGTERMs, 0 ECONNREFUSED, both valkey instances
healthy, Langfuse web/worker stable, chat completions 200 OK.
Sourcery review: valkey-cli ping without -p targets default 6379,
causing false negatives when VALKEY_CACHE_PORT is customized (e.g. dev=6389).
Now matches the port-aware pattern already used by valkey-lf probes.
- litellm/entrypoint.py: restore quote stripping before setdefault
  (prevents literal '"5432"' from breaking int() parsing)
- start-stack.sh: use ROUTER_IMAGE var instead of hardcoded
  ghcr.io/sheepdestroyer/llm-routing:latest in build/pull paths
- start-stack.sh: create volume dirs under DATA_ROOT instead of
  WORKDIR (fixes pod creation when DATA_ROOT != WORKDIR)
- start-stack.sh: add placeholder validation to render_litellm_config
  and chmod 644 on rendered configs for non-root container access
- scripts/backup.sh: use POD_NAME from .env instead of hardcoded
  agent-router-pod-postgres-db (fixes dev backup failures)
- router/main.py: extract _valkey_port() helper to DRY the
  VALKEY_CACHE_PORT/VALKEY_PORT fallback (3 call sites)
- router/main.py: replace hardcoded :3001 with LANGFUSE_WEB_PORT
  env var in dashboard Infrastructure Nodes display
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
- scripts/backup.sh: wire POSTGRES_PORT through pg_isready -p flag
  (fixes backup failures when DB port is customized, e.g. dev=5442)
- pod.yaml: remove redundant PORT env var (LITELLM_PORT already set)
- start-stack.sh: remove undocumented --pull-latest alias
- start-stack.sh: add placeholder validation to render_router_config
  (matches existing render_litellm_config guard)
- start-stack.sh: extract deploy_fresh_pod() helper to DRY the
  repeated generate→render→deploy→setup→verify sequence (4 call sites)
- router/main.py: use LLAMA_SERVER_URL for health check instead of
  hardcoded http://127.0.0.1:8080/health
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
- router/tests/test_get_redis.py: _valkey_port() now safely catches
  ValueError and returns 6379, so the old test that expected int('invalid')
  to crash inside get_redis() no longer applies. Split into two tests:
  test_valkey_port_invalid_fallback (new) and a rewritten
  test_get_redis_initialization_failure that uses aioredis.Redis
  side_effect instead.
- start-stack.sh: fix broken if/elif/else chain in first-deploy path
  (direct-applied commit had 'if' instead of 'elif', causing the
  localhost check and pull branch to run inside FULL_REBUILD mode,
  plus an extra dangling 'fi')
@sourcery-ai

sourcery-ai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR parameterizes all service ports and pod naming for prod/dev coexistence, fixes Valkey health checks by switching to exec probes and non-alpine images, and refactors deployment scripts/configs to be driven by env-based placeholders while addressing prior review comments and adding safer startup logic.

Sequence diagram for updated Valkey health checks with exec probes

sequenceDiagram
    participant Podman
    participant Valkey_cache
    participant Valkey_lf
    participant LivenessProbe
    participant ReadinessProbe

    Podman->>Valkey_cache: start valkey-server --port VALKEY_CACHE_PORT
    Podman->>Valkey_lf: start redis-server --port VALKEY_LF_PORT

    LivenessProbe->>Valkey_cache: valkey-cli -p VALKEY_CACHE_PORT ping
    Valkey_cache-->>LivenessProbe: PONG

    ReadinessProbe->>Valkey_cache: valkey-cli -p VALKEY_CACHE_PORT ping
    Valkey_cache-->>ReadinessProbe: PONG

    LivenessProbe->>Valkey_lf: valkey-cli -p VALKEY_LF_PORT -a REDIS_AUTH ping
    Valkey_lf-->>LivenessProbe: PONG

    ReadinessProbe->>Valkey_lf: valkey-cli -p VALKEY_LF_PORT -a REDIS_AUTH ping
    Valkey_lf-->>ReadinessProbe: PONG
Loading

Flow diagram for env-driven pod deployment via deploy_fresh_pod

flowchart TD
    A[start-stack_sh] --> B[generate_clickhouse_config]
    B --> C[render_litellm_config]
    C --> D[render_router_config]
    D --> E[render_pod_yaml]
    E --> F[podman_play_kube]
    F --> G[setup_minio_buckets]
    G --> H[verify_stack_health]

    subgraph Env_configuration
        P[POD_NAME]
        R[ROUTER_PORT]
        L[LITELLM_PORT]
        LC[VALKEY_CACHE_PORT]
        LF[VALKEY_LF_PORT]
        PG[POSTGRES_PORT]
        CH[CLICKHOUSE_*_PORT]
        M[MINIO_*_PORT]
        DR[DATA_ROOT]
        RI[ROUTER_IMAGE]
    end

    Env_configuration --> A
    DR --> B
    LC --> C
    R --> C
    L --> D
    Env_configuration --> E
Loading

File-Level Changes

Change Details Files
Make pod and service ports fully configurable via environment variables and propagate them through start scripts, health checks, and configs.
  • Add POD_NAME, ROUTER_PORT, LITELLM_PORT, LANGFUSE_WEB/WORKER_PORT, POSTGRES_PORT, Valkey, ClickHouse, and MinIO port envs with defaults in start-stack.sh and export them
  • Use DATA_ROOT for all volume hostPaths and create per-service data directories under DATA_ROOT
  • Replace hardcoded ports and pod names in start-stack.sh, health verification, MinIO setup, and backup scripts with env-driven values
  • Generate ClickHouse port override config from env and mount it into the container
start-stack.sh
scripts/backup.sh
pod.yaml
Switch Valkey health checks from tcpSocket to exec probes and remove BusyBox nc dependency that caused restart loops.
  • Change Valkey cache and Langfuse Valkey container images from alpine to non-alpine valkey:9.1.0
  • Update liveness/readiness probes to run valkey-cli ping using configured ports and auth
  • Ensure Langfuse Valkey container uses VALKEY_LF_PORT placeholders and passes REDIS_AUTH to health checks
pod.yaml
Introduce rendered LiteLLM and router configs that are port-aware and validated, and wire them into the pod via dedicated volumes.
  • Add render_litellm_config and render_router_config helpers to sed-replace port placeholders and write rendered configs under DATA_ROOT
  • Validate that no placeholders remain after rendering and set safe permissions (chmod 644) on generated files
  • Change pod.yaml volume mounts to use litellm-rendered and router-rendered hostPaths instead of source repo paths
start-stack.sh
litellm/config.yaml
router/config.yaml
pod.yaml
Refactor pod deployment logic into a reusable helper and enhance image selection flows for rebuild/pull operations.
  • Add deploy_fresh_pod() helper encapsulating ClickHouse config generation, config rendering, pod play, MinIO bucket setup, and health verification
  • Introduce PULL_MODE flag and --pull CLI option that pulls ROUTER_IMAGE from GHCR before redeploy
  • Make ROUTER_IMAGE configurable and update first-deploy logic to build local images only when needed or when FULL_REBUILD is set
start-stack.sh
Improve runtime robustness of LiteLLM entrypoint and router Valkey handling by safe env parsing and dynamic port usage.
  • Change litellm/entrypoint.py env loading to use setdefault so container envs override .env values
  • Add safe integer parsing for POSTGRES_PORT with fallback to 5432
  • Derive LiteLLM port from LITELLM_PORT/PORT env and use it when starting the proxy
  • Add _valkey_port() helper using VALKEY_CACHE_PORT/VALKEY_PORT with safe fallback and logging
  • Update router to use env-driven ports for LiteLLM, Langfuse, Valkey checks, memory proxy, dashboard, and health endpoints
litellm/entrypoint.py
router/main.py
router/tests/test_get_redis.py
Tighten pod.yaml env and probe wiring for Postgres, Langfuse, ClickHouse, MinIO and router to respect configured ports and URLs.
  • Parameterize DATABASE_URLs to use POSTGRES_PORT placeholders across services
  • Add PGPORT env for Postgres and include -p in pg_isready probes
  • Use LANGFUSE_WEB_PORT, CLICKHOUSE_HTTP/TCP_PORT, MINIO_S3/CONSOLE_PORT placeholders in Langfuse and MinIO envs and health checks
  • Set router image to ROUTER_IMAGE_PLACEHOLDER and make its liveness/readiness probes use ROUTER_PORT_PLACEHOLDER
pod.yaml
Add developer convenience for dev deployments and local testing.
  • Introduce start-dev.sh wrapper that sets DEV_ENV_FILE to .env.dev and delegates to start-stack.sh
  • Add .env.dev and ignore .venv/ in .gitignore to support isolated dev environments and virtualenv usage
  • Add scripts/dev-setup.sh (described in PR) for venv-based local test runs
start-dev.sh
.env.dev
.gitignore
scripts/dev-setup.sh

Possibly linked issues

  • #LHF-03: PR updates router/main.py and related configs to remove hardcoded service endpoints, using env-based URLs and ports.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@sheepdestroyer, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 24 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6ac705a0-e1ca-40c9-bdc4-617414b61ed2

📥 Commits

Reviewing files that changed from the base of the PR and between 3c2296e and dab8501.

📒 Files selected for processing (12)
  • .env.dev
  • .gitignore
  • README.md
  • litellm/config.yaml
  • litellm/entrypoint.py
  • pod.yaml
  • router/config.yaml
  • router/main.py
  • router/tests/test_get_redis.py
  • scripts/backup.sh
  • start-dev.sh
  • start-stack.sh
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/learn-deployment-guidelines

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.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The new --pull behaviour in start-stack.sh reuses ROUTER_IMAGE for both local builds and GHCR pulls; consider separating the local tag from the remote image (or deriving the remote reference from a fixed base plus version) to avoid confusion when ROUTER_IMAGE is set to a non-GHCR value.
  • There are now several places in router/main.py that independently resolve the LiteLLM and Langfuse ports from environment variables; extracting small helpers (similar to _valkey_port()) for these would reduce duplication and make port override behavior easier to maintain.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `--pull` behaviour in `start-stack.sh` reuses `ROUTER_IMAGE` for both local builds and GHCR pulls; consider separating the local tag from the remote image (or deriving the remote reference from a fixed base plus version) to avoid confusion when `ROUTER_IMAGE` is set to a non-GHCR value.
- There are now several places in `router/main.py` that independently resolve the LiteLLM and Langfuse ports from environment variables; extracting small helpers (similar to `_valkey_port()`) for these would reduce duplication and make port override behavior easier to maintain.

## Individual Comments

### Comment 1
<location path="pod.yaml" line_range="72" />
<code_context>
         - python3
         - -c
-        - import urllib.request; urllib.request.urlopen('http://localhost:4000/health/liveness')
+        - import urllib.request; urllib.request.urlopen('http://localhost:LITELLM_PORT_PLACEHOLDER/ping')
       initialDelaySeconds: 240
       periodSeconds: 15
</code_context>
<issue_to_address>
**issue (bug_risk):** Changing the LiteLLM liveness probe to `/ping` may not match the actual proxy endpoints.

The liveness probe was changed from `/health/liveness` to `/ping`, but the standard LiteLLM proxy only documents `/health/liveness` and `/health/readiness`. Unless you’ve explicitly added a `/ping` route, this endpoint may 404 and cause the pod to be marked unhealthy. Please either keep using the documented health endpoint or verify that `/ping` is implemented and stable across LiteLLM versions before relying on it in the probe.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread pod.yaml

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces support for a development environment overlay (.env.dev) to run a development stack (dev-router-pod) on distinct ports alongside production. It parameterizes ports, pod names, and image paths across the configuration files, entrypoints, and scripts, and adds a start-dev.sh wrapper. The review feedback highlights a bug in start-stack.sh where safe_pod_teardown falsely reports a timeout due to how podman pod exists behaves, a potential parsing issue with whitespace in .env keys in litellm/entrypoint.py, and several instances where empty environment variables could bypass default fallbacks in both litellm/entrypoint.py and router/main.py.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread start-stack.sh
Comment on lines +537 to 547
if podman pod exists ${POD_NAME} 2>/dev/null; then
echo "🛑 Gracefully stopping pod (SIGTERM, 30s timeout)..."
podman pod stop -t 30 agent-router-pod 2>/dev/null || true
podman pod stop -t 30 ${POD_NAME} 2>/dev/null || true
# If still running after graceful attempt, force-remove
if podman pod exists agent-router-pod 2>/dev/null; then
if podman pod exists ${POD_NAME} 2>/dev/null; then
echo "⚠️ Graceful stop timed out — force-removing..."
podman pod rm -f agent-router-pod 2>/dev/null || true
podman pod rm -f ${POD_NAME} 2>/dev/null || true
else
# Already stopped, just remove
podman pod rm agent-router-pod 2>/dev/null || true
podman pod rm ${POD_NAME} 2>/dev/null || true
fi

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The current implementation of safe_pod_teardown falsely reports a timeout and force-removes the pod even when the graceful stop was successful. This is because podman pod exists returns 0 (true) for stopped pods as well as running ones. Checking the exit status of podman pod stop is a much more reliable way to determine if the graceful stop succeeded.

Suggested change
if podman pod exists ${POD_NAME} 2>/dev/null; then
echo "🛑 Gracefully stopping pod (SIGTERM, 30s timeout)..."
podman pod stop -t 30 agent-router-pod 2>/dev/null || true
podman pod stop -t 30 ${POD_NAME} 2>/dev/null || true
# If still running after graceful attempt, force-remove
if podman pod exists agent-router-pod 2>/dev/null; then
if podman pod exists ${POD_NAME} 2>/dev/null; then
echo "⚠️ Graceful stop timed out — force-removing..."
podman pod rm -f agent-router-pod 2>/dev/null || true
podman pod rm -f ${POD_NAME} 2>/dev/null || true
else
# Already stopped, just remove
podman pod rm agent-router-pod 2>/dev/null || true
podman pod rm ${POD_NAME} 2>/dev/null || true
fi
if podman pod exists ${POD_NAME} 2>/dev/null; then
echo "🛑 Gracefully stopping pod (SIGTERM, 30s timeout)..."
if podman pod stop -t 30 ${POD_NAME} 2>/dev/null; then
podman pod rm ${POD_NAME} 2>/dev/null || true
else
echo "⚠️ Graceful stop timed out — force-removing..."
podman pod rm -f ${POD_NAME} 2>/dev/null || true
fi

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Good catch! Fixed in the follow-up PR: safe_pod_teardown now checks podman pod inspect --format '{{.State}}' instead of podman pod exists to distinguish running vs stopped pods. The old code would falsely report a timeout and force-remove even after a successful graceful stop.

Comment thread litellm/entrypoint.py
Comment on lines 18 to +20
key, _, val = line.partition("=")
val = val.strip().strip('"').strip("'")
os.environ[key] = val
os.environ.setdefault(key, val)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If the .env file contains spaces around the = sign (e.g., KEY = value), the parsed key will retain a trailing space (e.g., "KEY "). This prevents environment variables from being resolved correctly via os.environ.get("KEY"). Stripping the key ensures robust parsing.

Suggested change
key, _, val = line.partition("=")
val = val.strip().strip('"').strip("'")
os.environ[key] = val
os.environ.setdefault(key, val)
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip('"').strip("'")
os.environ.setdefault(key, val)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Good catch! Fixed in the follow-up PR: added key = key.strip() after line.partition("=") in the .env parser. Keys with trailing spaces (e.g. "KEY ") would previously fail to match in os.environ.get().

Comment thread litellm/entrypoint.py Outdated
Comment thread router/main.py Outdated
Comment on lines +26 to +28
LITELLM_URL = (os.getenv("LITELLM_ADMIN_URL") or f"http://127.0.0.1:{os.getenv('LITELLM_PORT', '4000')}").rstrip("/")
LLAMA_SERVER_URL = (os.getenv("LLAMA_SERVER_URL") or "http://127.0.0.1:8080").rstrip("/")
LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or "http://127.0.0.1:3001").rstrip("/")
LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or f"http://127.0.0.1:{os.getenv('LANGFUSE_WEB_PORT', '3001')}").rstrip("/")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If LITELLM_PORT or LANGFUSE_WEB_PORT is present in the environment but empty, os.getenv with a default argument will return "", resulting in invalid URLs like http://127.0.0.1:. Using or instead of the default argument in os.getenv ensures robust fallback behavior.

Suggested change
LITELLM_URL = (os.getenv("LITELLM_ADMIN_URL") or f"http://127.0.0.1:{os.getenv('LITELLM_PORT', '4000')}").rstrip("/")
LLAMA_SERVER_URL = (os.getenv("LLAMA_SERVER_URL") or "http://127.0.0.1:8080").rstrip("/")
LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or "http://127.0.0.1:3001").rstrip("/")
LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or f"http://127.0.0.1:{os.getenv('LANGFUSE_WEB_PORT', '3001')}").rstrip("/")
LITELLM_URL = (os.getenv("LITELLM_ADMIN_URL") or f"http://127.0.0.1:{os.getenv('LITELLM_PORT') or '4000'}").rstrip("/")
LLAMA_SERVER_URL = (os.getenv("LLAMA_SERVER_URL") or "http://127.0.0.1:8080").rstrip("/")
LANGFUSE_HOST = (os.getenv("LANGFUSE_HOST") or f"http://127.0.0.1:{os.getenv('LANGFUSE_WEB_PORT') or '3001'}").rstrip("/")

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Good catch! Fixed in the follow-up PR: all os.getenv('PORT', 'default') patterns in router/main.py and litellm/entrypoint.py now use os.getenv('PORT') or 'default' to handle empty-string env vars correctly. This prevents broken URLs like http://127.0.0.1: when a port var is set but empty.

sheepdestroyer and others added 2 commits July 11, 2026 21:58
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…ip, empty-string port handling

- safe_pod_teardown: use podman pod inspect --format '{{.State}}' instead of
  podman pod exists to distinguish running vs stopped pods (Gemini review)
- litellm/entrypoint.py: strip key after line.partition('=') to handle
  spaces around '=' in .env files (Gemini review)
- router/main.py + litellm/entrypoint.py: replace os.getenv('PORT', 'default')
  with os.getenv('PORT') or 'default' to handle empty-string env vars
  correctly, preventing broken URLs like http://127.0.0.1: (Gemini review)
- README.md: update health check table — valkey probes now use exec
  valkey-cli ping instead of tcpSocket, postgres uses pg_isready -p <port>
- Replied to false positives: LiteLLM /ping is a valid endpoint; the or
  chain in entrypoint.py correctly handles empty LITELLM_PORT
@sheepdestroyer

Copy link
Copy Markdown
Owner Author

Closing in favor of a fresh PR with all review fixes applied. See #253.

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.

1 participant