Skip to content

feat(deploy): migrate stack management from play kube to systemd Quadlets - #416

Closed
sheepdestroyer wants to merge 6 commits into
masterfrom
feat/quadlet-systemd-consolidated
Closed

feat(deploy): migrate stack management from play kube to systemd Quadlets#416
sheepdestroyer wants to merge 6 commits into
masterfrom
feat/quadlet-systemd-consolidated

Conversation

@sheepdestroyer

@sheepdestroyersheepdestroyer commented Aug 6, 2026

Copy link
Copy Markdown
Owner

Consolidated Quadlet systemd deployment for LLM-Routing.

Summary by Sourcery

Migrate stack deployment from a Podman play-kube pod to a systemd Quadlet-managed stack, introduce subdomain-based external URLs for services, and update verification, docs, and tests to match the new deployment and routing model.

Enhancements:

  • Add Quadlet rendering, installation, and ownership management to start-stack.sh, replacing direct podman play kube usage for stack lifecycle operations.
  • Derive external service URLs once in the startup script for consistent use across legacy YAML and Quadlet deployments.
  • Update external URL resolution logic to use service-specific subdomains (langfuse., litellm., llama.) with port preservation and improved host handling.
  • Extend the canonical endpoint verification script to construct URLs from PUBLIC_BASE_URL host and path while targeting service subdomains.
  • Adjust production upgrade tooling to sync Quadlet templates and ensure rendered units are secure and atomically updated.
  • Document the Quadlet-based deployment flow, systemd inspection commands, and updated container expectations in README and scripts README.

Tests:

  • Add static tests for Quadlet templates and renderer behavior, including container inventory, health checks, secrets hygiene, permissions, and upgrade integration.
  • Update router external URL tests to assert the new subdomain-based URL scheme and add coverage for requests without explicit ports.
  • Extend canonical URL verification expectations to cover new service URLs and llama.cpp health checks.

Summary by CodeRabbit

  • New Features

    • Added systemd-managed container deployment for the complete LLM routing stack.
    • Added integrated services for routing, observability, databases, caching, and object storage.
    • Service endpoints now use dedicated HTTPS subdomains for improved accessibility.
  • Bug Fixes

    • Improved external URL generation, including support for request ports and safer host handling.
    • Local llama services now connect reliably through local HTTP endpoints.
  • Documentation

    • Expanded deployment, restart, upgrade, diagnostics, and endpoint verification instructions.
  • Tests

    • Added validation for deployment configuration, health checks, permissions, and service startup behavior.

boy added 6 commits July 22, 2026 23:46
…lets
Replace 'podman play kube' with declarative Quadlet units rendered from
quadlets/*.pod + quadlets/*.container templates into
~/.config/containers/systemd/llm-routing/. systemd's podman-user-generator
turns them into llm-routing-*.service units, making systemd the single
supervisor: boot auto-start (WantedBy=default.target + linger) and crash
recovery (Restart=always) now come from systemd instead of podman's
restartPolicy.
Key points:
- Templates use the same _PLACEHOLDER convention as pod.yaml; a new
render_quadlets() in start-stack.sh reuses the existing env-derived
values (ports, secrets, DATA_ROOT, POD_NAME) so dev/prod parity is
preserved with plain string replacement (bare scalars, not YAML).
- deploy_fresh_pod() now: render configs -> render quadlets ->
daemon-reload -> start/restart llm-routing-pod.service. The bare
'restart existing' path and safe_pod_teardown() detect systemd-managed
stacks and route through systemctl accordingly.
- Entrypoint semantics: Quadlet Exec= only sets args (appended to the
image entrypoint), so containers where pod.yaml used command: now set
Entrypoint= explicitly (litellm venv python, valkey-server,
redis-server, /bin/sh for the router). MinIO keeps its image
entrypoint with Exec= providing the server args, matching pod.yaml
args: behavior.
- AddHost=<POD_NAME>:127.0.0.1 on all containers replicates the
/etc/hosts entry play kube injected, required by langfuse 3.222+
which resolves the pod hostname at startup.
- Healthchecks ported from livenessProbe exec commands (HealthCmd,
HealthStartPeriod maps initialDelaySeconds).
Verified on dev: all 9 containers healthy, 193/193 unit tests pass,
crash recovery (kill -> systemd auto-restart <12s), canonical HTTPS
endpoints green (model timeouts on free tier are pre-existing,
identical on prod play-kube).
@sourcery-ai

sourcery-aiBot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Migrates stack management from a Podman play kube-based pod to a systemd Quadlet-managed stack, introduces robust Quadlet rendering/deployment logic and ownership detection, and aligns external URL derivation and verification with new subdomain-based routing semantics.

File-Level Changes

ChangeDetailsFiles
Introduce Quadlet-based stack ownership detection and lifecycle management in start-stack.sh.
  • Define a canonical Quadlet unit name used across ownership, lifecycle, and diagnostics paths.
  • Add stack_ownership() to distinguish Quadlet-managed, legacy, and absent stacks via PODMAN_SYSTEMD_UNIT labels and systemd state.
  • Introduce require_user_systemd() to ensure a reachable systemd --user manager before Quadlet operations.
  • Update safe_pod_teardown() to reconcile Quadlet-owned stacks via systemd stop/reset-failed and fall back to legacy pod teardown when appropriate.
  • Change deployment flow to compute STACK_OWNERSHIP once and branch restart/replace behavior for Quadlet vs legacy stacks.
start-stack.sh
Add Quadlet rendering and deployment pipeline, replacing podman play kube for fresh deployments.
  • Add derive_external_service_urls() to compute proxy and NextAuth URLs once and export them for both YAML and Quadlet rendering.
  • Update render_pod_yaml() to consume pre-derived PROXY_BASE_URL_DERIVED and NEXTAUTH_URL_DERIVED instead of recomputing URLs in Python.
  • Introduce QUADLET_DIR and render_quadlets() to render quadlets/*.pod and *.container templates into owner-only units under ~/.config/containers/systemd/llm-routing, including placeholder substitution, unresolved-placeholder detection, Environment= quoting, and atomic staging/replacement.
  • Add deploy_quadlets() to render Quadlets, run systemctl --user daemon-reload, and start or restart the llm-routing-pod.service with clear error reporting.
  • Update deploy_fresh_pod() to call deploy_quadlets() instead of piping pod.yaml into podman play kube, and adjust success logging to use derived service URLs.
start-stack.sh
Define Quadlet templates for the entire stack and enforce deployment contracts with tests.
  • Add quadlets/*.container and llm-routing.pod templates describing the pod and its nine application containers with consistent Pod= and ContainerName= conventions.
  • Ensure each container includes health checks with HealthOnFailure=kill and Restart=always semantics for automatic recovery.
  • Create tests/test_quadlet_templates.py to validate container inventory, pod membership, healthcheck/restart policy, placeholder usage and absence of secrets, upgrade-prod sync behavior, file permission expectations, Environment= quoting, atomic rendering, and systemd failure handling hooks in start-stack.sh.
quadlets/llm-routing-clickhouse.container
quadlets/llm-routing-langfuse-web.container
quadlets/llm-routing-langfuse-worker.container
quadlets/llm-routing-litellm.container
quadlets/llm-routing-minio.container
quadlets/llm-routing-postgres.container
quadlets/llm-routing-router.container
quadlets/llm-routing-valkey-cache.container
quadlets/llm-routing-valkey-lf.container
quadlets/llm-routing.pod
tests/test_quadlet_templates.py
start-stack.sh
Align external URL resolution with subdomain-based routing and preserve public ports in canonical links.
  • Change resolve_external_urls() to generate service-specific subdomains (langfuse., litellm., llama.) based on either PUBLIC_BASE_URL or the incoming request host, stripping dashboard and service prefixes and preserving explicit ports when valid.
  • Improve error handling for invalid public ports and avoid leaking IPv6 fallback netlocs when a valid base request host is available.
  • Update router tests to assert the new subdomain-based external URLs and add coverage for base requests without ports.
  • Adjust scripts/verification/verify_canonical_endpoints.py to normalize PUBLIC_BASE_URL into a router_base URL, construct router endpoints from router_base, and build canonical service URLs using service subdomains over the same host and scheme.
router/main.py
router/tests/test_resolve_external_urls.py
scripts/verification/verify_canonical_endpoints.py
Update documentation and upgrade tooling for Quadlet-based deployment.
  • Revise README and scripts/README to describe Quadlet/systemd-based stack management, new start-stack.sh semantics, systemd inspection commands, and the nine application containers plus Podman infra container.
  • Clarify canonical URL testing expectations, including subdomain-based service URLs and local llama safety-net URLs that avoid dependence on TLS hostnames.
  • Enhance scripts/upgrade-prod.sh to include quadlets/ in required release contents, diff previews, user warnings, and rsync sync steps so Quadlet templates are deployed alongside other runtime files.
README.md
scripts/README.md
scripts/upgrade-prod.sh

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

@sheepdestroyer
sheepdestroyer deleted the feat/quadlet-systemd-consolidated branch August 6, 2026 18:25
@coderabbitai

coderabbitaiBot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2c7c767f-7596-4cb2-a71e-ae17acf535c9

📥 Commits

Reviewing files that changed from the base of the PR and between 2305be9 and f65b89e.

📒 Files selected for processing (19)
  • .env.dev
  • README.md
  • quadlets/llm-routing-clickhouse.container
  • quadlets/llm-routing-langfuse-web.container
  • quadlets/llm-routing-langfuse-worker.container
  • quadlets/llm-routing-litellm.container
  • quadlets/llm-routing-minio.container
  • quadlets/llm-routing-postgres.container
  • quadlets/llm-routing-router.container
  • quadlets/llm-routing-valkey-cache.container
  • quadlets/llm-routing-valkey-lf.container
  • quadlets/llm-routing.pod
  • router/main.py
  • router/tests/test_resolve_external_urls.py
  • scripts/README.md
  • scripts/upgrade-prod.sh
  • scripts/verification/verify_canonical_endpoints.py
  • start-stack.sh
  • tests/test_quadlet_templates.py

📝 Walkthrough

Walkthrough

The stack now uses systemd-managed Quadlets for deployment, adds nine service containers and a routing pod, derives service subdomain URLs, updates local llama endpoints, and expands endpoint verification, documentation, upgrade synchronization, and deployment contract tests.

Changes

LLM service URLs

Layer / File(s)Summary
Service URL contracts and resolution
.env.dev, router/main.py, router/tests/test_resolve_external_urls.py, start-stack.sh
Public services now use dedicated subdomains. URL resolution preserves valid request ports and removes path-based routing. Local llama endpoints use HTTP on port 8083.

Quadlet deployment

Layer / File(s)Summary
Quadlet service definitions
quadlets/*
Added the routing pod and nine container units for PostgreSQL, ClickHouse, MinIO, Valkey, LiteLLM, Langfuse, and the router. Units define dependencies, health checks, persistence, restart behavior, and startup timeouts.
Quadlet rendering and lifecycle
start-stack.sh, scripts/upgrade-prod.sh
Added Quadlet ownership detection, user-systemd validation, staged rendering, atomic installation, stale-unit removal, systemd lifecycle handling, and Quadlet synchronization during upgrades.

Verification and documentation

Layer / File(s)Summary
Verification and operational support
tests/test_quadlet_templates.py, scripts/verification/verify_canonical_endpoints.py, README.md, scripts/README.md
Added Quadlet contract tests and expanded canonical endpoint checks. Documentation now covers systemd operations, Quadlet inspection, container counts, service URLs, and local llama-server requirements.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
participant StartStack
participant UserSystemd
participant QuadletUnits
participant LLMRoutingPod
StartStack->>UserSystemd: reload and start or restart rendered units
UserSystemd->>QuadletUnits: generate and manage service units
QuadletUnits->>LLMRoutingPod: create or reconcile the routing pod
LLMRoutingPod-->>StartStack: report startup or failure status
Loading

Possibly related PRs

Suggested labels:documentation, router, scripts, tests

✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch feat/quadlet-systemd-consolidated
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/quadlet-systemd-consolidated

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-aisourcery-aiBot 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 Quadlet renderer in start-stack.sh dereferences several environment variables with os.environ[...] (e.g. OLLAMA_API_KEY, OPENROUTER_API_KEY, LANGFUSE_PUBLIC_KEY, etc.), which will hard-fail the deployment if any are missing; consider using os.environ.get() with sane defaults for non-critical secrets to avoid making them implicitly mandatory.
  • The new derive_external_service_urls shell/Python helper, resolve_external_urls in router/main.py, and the canonical URL verifier now each embed slightly different URL derivation logic for the same services; it would be safer to centralize this computation (or at least a shared reference implementation) to reduce the risk of these paths drifting over time.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments- The Quadlet renderer in `start-stack.sh` dereferences several environment variables with `os.environ[...]` (e.g. `OLLAMA_API_KEY`, `OPENROUTER_API_KEY`, `LANGFUSE_PUBLIC_KEY`, etc.), which will hard-fail the deployment if any are missing; consider using `os.environ.get()` with sane defaults for non-critical secrets to avoid making them implicitly mandatory.
- The new `derive_external_service_urls` shell/Python helper, `resolve_external_urls` in `router/main.py`, and the canonical URL verifier now each embed slightly different URL derivation logic for the same services; it would be safer to centralize this computation (or at least a shared reference implementation) to reduce the risk of these paths drifting over time.
## Individual Comments### Comment 1
<locationpath="start-stack.sh"line_range="597-608" />
<code_context>
+import os
+from urllib.parse import urlparse
+public = (os.environ.get("PUBLIC_BASE_URL") or "").rstrip("/")
+routing_domain = os.environ.get("ROUTING_DOMAIN") or "vendeuvre.lan"
+parsed = urlparse(public if "://" in public else f"https://{public}")
+scheme = parsed.scheme if parsed.scheme in {"http", "https"} else "https"
+host = parsed.netloc or parsed.path.split("/", 1)[0] or routing_domain
+print(os.environ.get("PROXY_BASE_URL") or f"{scheme}://litellm.{host}")
+print(os.environ.get("NEXTAUTH_URL") or f"{scheme}://langfuse.{host}")
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Defaulting to a hard-coded routing domain when PUBLIC_BASE_URL is empty may surprise operators.
When `PUBLIC_BASE_URL` is empty you fall back to `routing_domain`, which defaults to the literal `"vendeuvre.lan"`. So a missing `PUBLIC_BASE_URL` and `ROUTING_DOMAIN` will silently produce URLs like `https://litellm.vendeuvre.lan`.
If this default is only valid in a specific environment, consider instead:
- Failing fast when both `PUBLIC_BASE_URL` and `ROUTING_DOMAIN` are unset, or
- Emitting a clear warning to stderr when the hard-coded default is used.
This makes configuration errors more visible and avoids hard-to-diagnose connectivity issues.
```suggestion local values values=$(python3 -c 'import osimport sysfrom urllib.parse import urlparsepublic = (os.environ.get("PUBLIC_BASE_URL") or "").rstrip("/")routing_domain = os.environ.get("ROUTING_DOMAIN") or ""# Fail fast if both PUBLIC_BASE_URL and ROUTING_DOMAIN are unset/emptyif not public and not routing_domain: print( "ERROR: PUBLIC_BASE_URL and ROUTING_DOMAIN are both unset; " "cannot derive external service URLs.", file=sys.stderr, ) sys.exit(1)# Warn when using the hard-coded default routing domainif not routing_domain: routing_domain = "vendeuvre.lan" print( \'WARNING: Using default routing domain "vendeuvre.lan". ' "Set ROUTING_DOMAIN or PUBLIC_BASE_URL to override.", file=sys.stderr, )# If PUBLIC_BASE_URL is set, use it; otherwise derive from routing_domainbase_for_parse = public if public else routing_domainparsed = urlparse(base_for_parse if "://" in base_for_parse else f"https://{base_for_parse}")scheme = parsed.scheme if parsed.scheme in {"http", "https"} else "https"host = parsed.netloc or parsed.path.split("/", 1)[0] or routing_domain# Only the derived URLs go to stdout; warnings/errors go to stderr aboveprint(os.environ.get("PROXY_BASE_URL") or f"{scheme}://litellm.{host}")print(os.environ.get("NEXTAUTH_URL") or f"{scheme}://langfuse.{host}")') || return 1```
</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 threadstart-stack.sh
Comment on lines +597 to +608
local values
values=$(python3 -c '
import os
from urllib.parse import urlparse
public = (os.environ.get("PUBLIC_BASE_URL") or "").rstrip("/")
routing_domain = os.environ.get("ROUTING_DOMAIN") or "vendeuvre.lan"
parsed = urlparse(public if "://" in public else f"https://{public}")
scheme = parsed.scheme if parsed.scheme in {"http", "https"} else "https"
host = parsed.netloc or parsed.path.split("/", 1)[0] or routing_domain
print(os.environ.get("PROXY_BASE_URL") or f"{scheme}://litellm.{host}")
print(os.environ.get("NEXTAUTH_URL") or f"{scheme}://langfuse.{host}")
') || return 1

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.

suggestion (bug_risk): Defaulting to a hard-coded routing domain when PUBLIC_BASE_URL is empty may surprise operators.

When PUBLIC_BASE_URL is empty you fall back to routing_domain, which defaults to the literal "vendeuvre.lan". So a missing PUBLIC_BASE_URL and ROUTING_DOMAIN will silently produce URLs like https://litellm.vendeuvre.lan.

If this default is only valid in a specific environment, consider instead:

  • Failing fast when both PUBLIC_BASE_URL and ROUTING_DOMAIN are unset, or
  • Emitting a clear warning to stderr when the hard-coded default is used.

This makes configuration errors more visible and avoids hard-to-diagnose connectivity issues.

Suggested change
local values
values=$(python3 -c '
import os
from urllib.parse import urlparse
public = (os.environ.get("PUBLIC_BASE_URL") or "").rstrip("/")
routing_domain = os.environ.get("ROUTING_DOMAIN") or "vendeuvre.lan"
parsed = urlparse(public if"://"in public else f"https://{public}")
scheme = parsed.scheme if parsed.scheme in {"http", "https"} else"https"
host = parsed.netloc or parsed.path.split("/", 1)[0] or routing_domain
print(os.environ.get("PROXY_BASE_URL") or f"{scheme}://litellm.{host}")
print(os.environ.get("NEXTAUTH_URL") or f"{scheme}://langfuse.{host}")
') || return 1
local values
values=$(python3 -c '
import os
import sys
from urllib.parse import urlparse
public = (os.environ.get("PUBLIC_BASE_URL") or "").rstrip("/")
routing_domain = os.environ.get("ROUTING_DOMAIN") or ""
# Fail fast if both PUBLIC_BASE_URL and ROUTING_DOMAIN are unset/empty
if not public and not routing_domain:
print(
"ERROR: PUBLIC_BASE_URL and ROUTING_DOMAIN are both unset; "
"cannot derive external service URLs.",
file=sys.stderr,
)
sys.exit(1)
# Warn when using the hard-coded default routing domain
if not routing_domain:
routing_domain = "vendeuvre.lan"
print(
\'WARNING: Using default routing domain "vendeuvre.lan". '
"Set ROUTING_DOMAIN or PUBLIC_BASE_URL to override.",
file=sys.stderr,
)
# If PUBLIC_BASE_URL is set, use it; otherwise derive from routing_domain
base_for_parse = public if public else routing_domain
parsed = urlparse(base_for_parse if"://"in base_for_parse else f"https://{base_for_parse}")
scheme = parsed.scheme if parsed.scheme in {"http", "https"} else"https"
host = parsed.netloc or parsed.path.split("/", 1)[0] or routing_domain
# Only the derived URLs go to stdout; warnings/errors go to stderr above
print(os.environ.get("PROXY_BASE_URL") or f"{scheme}://litellm.{host}")
print(os.environ.get("NEXTAUTH_URL") or f"{scheme}://langfuse.{host}")
') || return 1

Sign up for freeto 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

@sheepdestroyer