# VPS deploy, compose-style, kardeş servislerle aynı şekil (hata toparlama ucuz): # # Validate — tüm modüllerin derleme kontrolü, kendi runner'ında. # Build and test — bağımlılıklar + `python -m pytest tests/unit -q` # süiti (katalog/uygulama doğrulaması dahil), sonra repo # Containerfile'ından imaj (ENV bloğu dağıtım # varsayılanlarının TEK kaynağıdır) ve imaj tarball'ı + # compose dosyaları koşunun artefaktı olarak yüklenir. # Deploy — push'ta OTOMATIK: SSH ile kapasite ön kontrolü, imajı # yükle, deploy sahipli stack.env'in HEZARFEN_TAG'ini # BU KOŞUNUN artefaktına çevir, compose.yaml + unit'i # kur, stack'i yeniden başlat, `/health` ve `/ready` # kapılarını geçir, olmazsa önceki tag'e dön. Yani yeşil # bir push servisi kendiliğinden günceller. # # KAPASİTE KAPISI DEĞİŞMEDİ (kullanıcı kararı 2026-09-23: yeşil push artık # kendiliğinden deploy eder; 2026-09-15'teki "yalnız elle" kararı kalktı). # Eşik hâlâ compose.yaml `x-rag-envelope` bloğundan OKUNUR — tek kaynak; # sayıyı buraya ikinci kez yazmak, model çağından kalma 12 GB eşiğinin # sessizce geri gelmesi demekti. Yetmezse deploy sayılarıyla reddeder, # eşiği gevşetmez. Gömme ve rerank UZAK API'de (dağıtım varsayılanı = api) # → yerel modeller (~4,5 GB) indirilmez; ölçülen zarf torch ~0,4 GB + # 0,53 GB/10k chunk = 1,1 GB (tek korpus) … 2,6 GB (3 korpus), bkz. # PROJECT_STATE §11.2. # Operatör yerel yola (RAG_EMBED_PROVIDER=local) dönerse zarf büyür ve # GPU'suz makinede rerank 95,9 s sürer: ürün kapısı O-05 p50 <= 6 s # GEÇİLMEZ — o yapılandırma için eşiği sunucuya elle yükseltmek gerekir. # # Validate ile Build and test paralel koşar; Deploy ikisi de yeşilse # çalışır ve BU KOŞUNUN artefaktını alır (en yeni yeşil araması değil). # Yeni bir push aynı ref'teki Validate/Build'i iptal eder; uçuştaki # Deploy'u ASLA iptal etmez (iki deploy iç içe girerse stack karışır). # # workflow_dispatch (Actions -> Run workflow, ya da # `gh workflow run main.yml --ref main`) süiti koşmadan en yeni yeşil # build'in artefaktını yeniden deploy eder. `tests: force` önce bu # ref'i derler ve test eder, sonra O KOŞUNUN taze artefaktını alır. # # TWO TEST PATHS — the default is the full one (same shape as hezarfen_backend): # # DEFAULT Push it and let GitHub do everything: suite, image, bundle, # artifact, and — when Validate and Build are both green — # deploy of THIS run's artifact. This is also the recovery # path when the local machine is unavailable. # SPECIAL Prove the suite on your own machine first (scripts/gate-local.sh # — ~32 s here). The suite currently HANGS on the runner: run # 35297989416 sat at 7% for 73 minutes until it was cancelled by # hand, so this lane is the fast one. The script prints (or, with # --amend, appends) a `Local-Gate: ( passed, s)` # trailer; the "Decide test gate" step verifies it against # HEAD^{tree} and only then skips the runner suite — CI still # builds the image, proves it API-only, stages, uploads and # deploys this run's artifact. # A stale or copy-pasted trailer silently falls back to running # the suite, so the fallback costs time, never verification. # Opt the pre-push hook in per clone: # git config core.hooksPath .githooks # # Bir seferlik ön koşullar (workflow'un erişimi dışında): # * repo secret'ları SSH_PRIVATE_KEY / SSH_HOST / SSH_USER; # * sunucuda `loginctl enable-linger `; # * sunucuda podman + bir compose sağlayıcı; # * operatörün ~/hezarfen_rag/hezarfen_rag.env dosyası # (şablon: deploy/hezarfen_rag.env.example) ve ~/hezarfen_rag/data/ # korpusu (imgeye girmez, salt-okunur bağlanır). name: VPS deploy on: push: branches: - main # Elle yeniden deploy kapısı — yukarıdaki başlık yorumuna bakın. # auto/skip: en yeni yeşil artefaktı yeniden deploy eder (süit tekrar # ödenmez). force: bu ref'i önce derler ve test eder, o taze artefaktı # deploy eder. workflow_dispatch: inputs: tests: description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first." type: choice options: - auto - skip - force default: auto # Deploy serileştirmesi işin kendisinde: yeni bir push, uçuştaki VPS değişimine # dokunmadan bayat Validate/Build'i iptal edebilmeli. permissions: contents: read # workflow_dispatch yolu `gh run list/view` ile en yeni yeşil koşuyu arar ve o # koşunun artefaktini indirir; ikisi de Actions API'sidir ve YAZMA GEREKMEZ. actions: read env: SERVICE: hezarfen_rag_compose DEPLOY_SUBDIR: hezarfen_rag ENV_FILE_NAME: hezarfen_rag.env # Servisin portu (imaj ENV'i ile aynı; kapı bu portu yoklar). PORT: "8000" # Kapı bütçesi: `/ready` boru hattının kurulmasını bekler. API sağlayıcı # yolunda (dağıtım varsayılanı) model İNDİRİLMEZ; korpus kurulumu uzak gömme # çağrılarıyla saniyeler sürer. Bütçe yine cömert: operatör `local` seçerse # soğuk model volume'u GB'larca indirir (ölçüldü: ~4,5 GB). READY_TIMEOUT: "900" jobs: validate: name: Validate if: github.event_name == 'push' runs-on: ubuntu-24.04 concurrency: group: ci-${{ github.workflow }}-${{ github.ref }}-validate cancel-in-progress: true steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: # Containerfile ile aynı satır (python:3.11-slim). python-version: "3.11" - name: Compile every module run: python -m compileall -q src tests build: name: Build and test # Pushes always build (and, by default, test). A manual redeploy reuses the # newest green artifact instead of paying the suite again, unless the # dispatch asks for `tests: force`, which builds and tests this ref. if: github.event_name == 'push' || github.event.inputs.tests == 'force' runs-on: ubuntu-24.04 concurrency: group: ci-${{ github.workflow }}-${{ github.ref }}-build cancel-in-progress: true steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" # ── Which test path this run takes ────────────────────────────────── # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was # already through the suite on the developer's machine # (scripts/gate-local.sh prints it; --amend appends it), so this run # only builds, packs and uploads. # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so # a stale or copy-pasted trailer silently falls back to running the # suite. The log always says which branch was taken, and why. # Trailer shape: `Local-Gate: <40-hex tree> ( passed, s)`. - name: Decide test gate id: gate run: | set -euo pipefail # Only reaches here on a push, or a dispatch with tests=force (the # job-level `if` skips the other dispatch modes) — and force means # the caller explicitly asked for the suite. mode='${{ github.event.inputs.tests }}' tree=$(git rev-parse HEAD^{tree}) if [ "$mode" = force ]; then echo "workflow_dispatch tests=force ⇒ running the suite on this ref" echo "skip=false" >> "$GITHUB_OUTPUT" exit 0 fi claim=$(git log -1 --format=%B \ | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \ | tail -1) if [ -z "$claim" ]; then echo "no Local-Gate trailer on $(git rev-parse --short HEAD) ⇒ running the suite (the default path)" echo "skip=false" >> "$GITHUB_OUTPUT" elif [ "${claim%%|*}" != "$tree" ]; then echo "local gate claims tree ${claim%%|*}; actual tree $tree ⇒ running tests anyway" echo "skip=false" >> "$GITHUB_OUTPUT" else echo "local gate trailer matches tree $tree ⇒ skipping the suite (${claim#*|})" echo "skip=true" >> "$GITHUB_OUTPUT" fi # CPU tekerleği: CI'da GPU yok ve GPU imajı ~2,5 GB daha büyük. # Testler ÜÇ listeyi de ister: servis yolu (requirements.txt), yerel model # yığını (requirements-local.txt) ve eval (requirements-eval.txt — yalnız # CI/geliştirme; imaja girmez). # The runner's pip environment exists ONLY to run the suite: the image # builds its dependencies inside the Containerfile, and the API-only # proof runs them inside the image. Skipped when the local gate already # proved the suite. - name: Install dependencies (CPU torch) if: steps.gate.outputs.skip != 'true' run: | set -euo pipefail pip install --no-cache-dir "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu pip install --no-cache-dir --requirement requirements.txt \ --requirement requirements-local.txt \ --requirement requirements-eval.txt # Bozuk bir build sunucuya ASLA ulaşmamalı: ölçüm kapıları ve regresyon # süiti burada koşar. Ortam gerektiren testler (korpus, OCR dil verisi, # model indirmesi) KENDİLERİ atlar ve nedenini yazar; ağır # integration/e2e koşumları model indirdiği için CI kapısı DEĞİLDİR — # bkz. README "CI deploy". # `timeout --foreground 600` (10 min) bounds the step at the shell level, # unbuffered and unpiped: what pytest printed up to the kill survives. # 600 s is measured, not guessed — every green run's Test step took 41 s # (35248848296, 35246056805, 35235114053, `pip install pytest` included), # so this is ~15x the worst green, and it turns a stall from the hours it # has actually burned (73 min stuck at 7% on 35297989416, 3 h 20 min on # 35283445041) into ten minutes. `-u` is what keeps the progress line # flowing into the log while the suite runs. # faulthandler is the layer that NAMES the hang: after 120 s inside a # single test (4x this machine's whole-suite 32 s, 3x the whole green CI # step) it dumps every thread's traceback and exits 1. Core pytest, so no # extra install and no plugin that could change the suite's semantics. - name: Test if: steps.gate.outputs.skip != 'true' run: | set -euo pipefail pip install --no-cache-dir pytest timeout --foreground 600 \ python -u -m pytest tests/unit -q \ -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True # Always *within the test path*, including when the step above was # killed: the discriminator. Disk or memory starvation shows here; a # pytest process still standing after `timeout` returns is the signature # of a kill the kernel could not deliver. - name: Stall diagnostics if: always() && steps.gate.outputs.skip != 'true' run: | echo '=== df -h / ==='; df -h / || true echo '=== free -m ==='; free -m || true echo '=== nproc ==='; nproc || true echo '=== surviving pytest processes ===' ps -eo pid,etimes,stat,cmd | grep '[p]ytest' || echo none # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o # gönderilir, ayrı bir CI ikizi yok. - name: Build the image run: | set -euo pipefail docker build -f Containerfile -t localhost/hezarfen_rag:$GITHUB_SHA . # VARSAYILAN İMGE KÜÇÜK MÜ (kullanıcı kararı 2026-09-17): yerel yığın # (torch/FlagEmbedding/ağırlıklar) İMAĞA GİRMEZ; yerel yol bir EKLENTİ # VOLUME'u ile açılır (deploy/provision_local_stack.sh). Bu iddialar # imajın kendisinde ölçülür (runner'da torch KURULU, yani runner'da # ölçmek yanıltıcı olurdu). # Every assertion here is an EXIT CODE or a CAPTURED STRING, never a # pipeline's status: a refusal is *supposed* to exit non-zero # (src/service/preflight.py -> `return 2` / `SystemExit(2)`), so the old # `docker run … 2>&1 | grep -q …` under `set -o pipefail` handed that 2 # back as the STEP's own status and killed a check that had actually # passed (job 35303767476, exit 2, with the expected line in the log). # Capturing first keeps the two facts separable — the message is asserted # on $local_out, the code on $local_rc. - name: Prove the default image is API-only and refuses `local` cleanly run: | set -euo pipefail img=localhost/hezarfen_rag:$GITHUB_SHA # 1. torch must be ABSENT inside the image: `python -c` exits 1 when it # is present, and that non-zero code IS the assertion. docker run --rm "$img" python -c "import importlib.util, sys; sys.exit(1 if importlib.util.find_spec('torch') else 0)" common=(--env RAG_ALLOW_UNCALIBRATED_ABSTAIN=1 --env LLM_API_KEY=ci) # 2. the shipped default (api) must come up green: exit 0 is the assertion. docker run --rm "${common[@]}" \ --env RAG_EMBED_PROVIDER=api --env RAG_EMBED_API_BASE=https://ornek/v1 \ --env RAG_EMBED_MODEL=m --env RAG_EMBED_API_KEY=k \ --env RAG_RERANK_PROVIDER=api --env RAG_RERANK_API_URL=https://ornek/rerank \ --env RAG_RERANK_MODEL=m --env RAG_RERANK_API_KEY=k \ "$img" python -m src.service.preflight # 3. `local` must REFUSE — asserted twice, and neither assertion can be # fooled by the other: the code must be non-zero, the message must # name the provisioning script. local_env=(--env RAG_EMBED_PROVIDER=local --env RAG_RERANK_PROVIDER=local) local_rc=0 local_out=$(docker run --rm "${common[@]}" "${local_env[@]}" "$img" \ python -m src.service.preflight 2>&1) || local_rc=$? printf '%s\n' "$local_out" if [ "$local_rc" -eq 0 ]; then echo "local secimi kucuk imgede GECMEMELIYDI (exit 0)" >&2 exit 1 fi if ! printf '%s\n' "$local_out" | grep -q 'provision_local_stack.sh'; then echo "ret metni saglama betigini adiyla soylemiyor (exit $local_rc)" >&2 exit 1 fi echo "kucuk imge dogrulandi: torch yok; api yolu yesil; local yolu exit $local_rc ile ret + ret metni saglama betigini adiyla soyluyor" - name: Stage the release bundle run: | set -euo pipefail mkdir -p stage docker save localhost/hezarfen_rag:$GITHUB_SHA | gzip > stage/hezarfen_rag.tar.gz cp compose.yaml deploy/hezarfen_rag_compose.service stage/ echo -n "$GITHUB_SHA" > stage/tag test -f stage/hezarfen_rag.tar.gz test -f stage/compose.yaml test -f stage/hezarfen_rag_compose.service test -f stage/tag ls -lh stage - name: Upload the release uses: actions/upload-artifact@v4 with: name: release path: stage retention-days: 30 deploy: name: Deploy needs: [validate, build] concurrency: group: deploy cancel-in-progress: false # Push: yalnız validate VE build yeşilse — ikisi de sunucuyu kapılar; # artefakt BU KOŞUNUNKİDİR (aşağıda needs.build.result == success). # Dispatch: mevcut yol. auto/skip iki CI işini atlar ve en yeni yeşil # build'i alır; tests=force build'i koşar ve bu koşunun artefaktını # alır. `always()` atlamanın kapıdan geçmesini engeller. if: >- always() && ((needs.validate.result == 'success' && needs.build.result == 'success') || (github.event_name == 'workflow_dispatch' && (needs.validate.result == 'skipped' || needs.validate.result == 'success') && (needs.build.result == 'skipped' || needs.build.result == 'success'))) runs-on: ubuntu-24.04 steps: # Dispatch ve bu koşuda build YOKSA (auto/skip): BUILD işi yeşil olan # en yeni push koşusunu alır. Push ve tests=force buraya düşmez — # onların artefaktı aşağıdaki adımdır. - name: Find the newest green build if: needs.build.result == 'skipped' env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail run_id="" for rid in $(gh run list -R "$GITHUB_REPOSITORY" --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do if [ "$(gh run view -R "$GITHUB_REPOSITORY" "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then run_id=$rid break fi done if [ -z "$run_id" ]; then echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2 exit 1 fi echo "deploying the release from run $run_id" echo "run_id=$run_id" >> "$GITHUB_ENV" - name: Fetch the green release if: needs.build.result == 'skipped' uses: actions/download-artifact@v4 with: name: release path: stage run-id: ${{ env.run_id }} github-token: ${{ github.token }} # Push, ve tests=force: artefakt bu koşunun kendisinin ürettiği sürüm. - name: Fetch this run's release if: needs.build.result == 'success' uses: actions/download-artifact@v4 with: name: release path: stage - name: Check the release is complete run: | set -euo pipefail test -f stage/hezarfen_rag.tar.gz test -f stage/compose.yaml test -f stage/hezarfen_rag_compose.service test -f stage/tag - name: Install SSH keys run: | mkdir -p ~/.ssh echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts - name: Upload the release run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' set -euo pipefail case "$1" in ''|/*|*..*) echo "Refusing a broad deploy subdirectory: '$1'" >&2 exit 1 ;; esac deploy_path=$HOME/$1 mkdir -p -- "$deploy_path" REMOTE tar -C stage -czf - hezarfen_rag.tar.gz compose.yaml hezarfen_rag_compose.service tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'" - name: Load the image and restart the service run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME' '$PORT' '$READY_TIMEOUT'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 service=$2 env_file=$deploy_path/$3 port=$4 ready_timeout=$5 export XDG_RUNTIME_DIR=/run/user/$(id -u) cd -- "$deploy_path" if [ ! -f "$env_file" ]; then echo "missing $env_file — create it (0600) from the repo's deploy/hezarfen_rag.env.example" >&2 exit 1 fi chmod 0600 -- "$env_file" # OPERATOR ORTAMI SURECE ALINIR. podman-compose interpolasyonu ORTAM # DEGISKENLERINE bakar ve `--env-file` YALNIZ SON dosyayi cozer # (podman_compose.py:2941-2946, :2559): iki dosyali cagri operator # dosyasini tamamen dusuruyordu. RAG'da bu "required variable ... # is missing" DEGIL, SESSIZ bir yanlis-korpus olarak gorunurdu: # compose.yaml'daki BOOK_PATH/SINIF/DERS interpolasyonu cihaz # varsayilanina (10/biyoloji) duser ve `environment:` env_file'i # ezdigi icin konteyner operatorun kitabini HIC gormez. Bu yuzden # dosya satir satir okunur -- kabuk genisletmesi YOK (deger icindeki # `$` oldugu gibi kalir), systemd `EnvironmentFile=` ile AYNI # davranis (satir-ici `#` korunur; bkz. unit notu). while IFS= read -r satir || [ -n "$satir" ]; do case "$satir" in ''|'#'*) continue ;; esac anahtar=${satir%%=*} deger=${satir#*=} case "$anahtar" in ''|*[!A-Za-z0-9_]*) echo "operator env: gecersiz anahtar adi -- harf/rakam/alt cizgi beklenirdi" >&2 exit 1 ;; esac export "$anahtar=$deger" done < "$env_file" # KAPASİTE ÖN KONTROLÜ — EŞİKLER TEK KAYNAKTAN: compose.yaml'daki # `x-rag-envelope`. Ölçülmüş zarf (API sağlayıcı yolu): torch ~0,4 GB # + 0,53 GB/10k chunk = 1,1 GB (tek korpus) … 2,6 GB (3 korpus); # mem_limit_mb aynı zamanda host RAM eşiğidir (kap tavanına kadar # çıkabilmeli). Diskte imaj + rollback için ÖNCEKİ imaj da durur. # Blok okunamazsa kapı ölçülemez: sessizce devam etmek yerine reddet. envelope_kaynak="compose.yaml" mem_limit_mb=$(awk '/^x-rag-envelope:/{f=1} f&&/^[[:space:]]+mem_limit_mb:/{print $2; exit}' "$envelope_kaynak") disk_min_gb=$(awk '/^x-rag-envelope:/{f=1} f&&/^[[:space:]]+disk_min_gb:/{print $2; exit}' "$envelope_kaynak") case "${mem_limit_mb}:${disk_min_gb}" in *[!0-9:]*|:*|*:) echo "compose.yaml: x-rag-envelope okunamadi (mem_limit_mb=${mem_limit_mb} disk_min_gb=${disk_min_gb}); kapasite kapisi olculemez -> deploy reddedildi" >&2 exit 1 ;; esac avail_mb=$(awk '/MemAvailable/ {print int($2/1024)}' /proc/meminfo) disk_gb=$(df -BG --output=avail "$deploy_path" | tail -1 | tr -dc '0-9') if [ "$avail_mb" -lt "$mem_limit_mb" ] || [ "$disk_gb" -lt "$disk_min_gb" ]; then echo "refusing to deploy: ${avail_mb} MB RAM available (need >= ${mem_limit_mb}) and ${disk_gb} GB disk (need >= ${disk_min_gb})." >&2 echo "envelope from compose.yaml x-rag-envelope; with API providers the local models (~4.5 GB) never enter the image (a 'local' provider selection needs its own, larger envelope and a GPU)." >&2 exit 1 fi command -v podman >/dev/null || { echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2 exit 1 } podman compose version >/dev/null 2>&1 || { echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2 exit 1 } gunzip -c "$deploy_path/hezarfen_rag.tar.gz" | podman load tag=$(cat -- "$deploy_path/tag") if [ -f "$deploy_path/current_tag" ]; then cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag" fi printf '%s\n' "$tag" > "$deploy_path/current_tag" # stack.env deploy sahipli (operatorun ayar dosyasindan farkli): # yalniz imaj tag'ini tasir ve compose'a giden TEK `--env-file` odur # -- operator degerleri yukarida surece alindi (EnvironmentFile= ile # ayni iki-kanal deseni). Iki dosyali cagri bu saglayicida operator # dosyasini dusurur (podman_compose.py:2941-2946, :2559); ortam # degiskeni --env-file degerlerini ezer (:2562). printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env" chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_rag_compose.service" rm -f -- "$deploy_path/hezarfen_rag.tar.gz" compose_up() { podman compose --profile product --env-file "$deploy_path/stack.env" up -d --no-build } rollback() { if [ -f "$deploy_path/previous_tag" ]; then prev=$(cat -- "$deploy_path/previous_tag") printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env" printf '%s\n' "$prev" > "$deploy_path/current_tag" compose_up echo "rolled back to $prev" >&2 else # İlk deploy: geri dönülecek imaj yok. `-v` YOK — model cache ve # maliyet defteri volume'ları korunur. podman compose --profile product --env-file "$deploy_path/stack.env" down echo 'first deploy failed; stack stopped, volumes kept' >&2 fi } mkdir -p -- "$HOME/.config/systemd/user" install -m 0644 -- "$deploy_path/hezarfen_rag_compose.service" "$HOME/.config/systemd/user/$service.service" systemctl --user daemon-reload systemctl --user enable -- "$service" systemctl --user restart "$service" || true # Kapı 1 — liveness: süreç ayağa kalktı mı (boru hattı arkada kurulur). live_ok=0 for _ in $(seq 1 60); do served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || true case "$served" in *'"status":"ok"'*) live_ok=1; break ;; esac sleep 1 done if [ "$live_ok" -ne 1 ]; then echo '/health never answered ok; rolling back' >&2 podman logs --tail 30 hezarfen_rag 2>&1 >&2 || true rollback exit 1 fi # Kapı 2 — readiness: boru hattı GERÇEKTEN kuruldu mu (#50: `/health` # servis bozukken de ok döner). Soğuk model volume'unda bu adım # indirmeleri bekler; bütçe READY_TIMEOUT saniyedir. ready_ok=0 for _ in $(seq 1 "$ready_timeout"); do served=$(curl -fsS "http://127.0.0.1:$port/ready" 2>/dev/null) || true case "$served" in *'"status":"ready"'*) ready_ok=1; break ;; esac sleep 1 done if [ "$ready_ok" -ne 1 ]; then echo "/ready never became ready within ${ready_timeout}s; rolling back" >&2 curl -sS "http://127.0.0.1:$port/ready" >&2 || true podman logs --tail 30 hezarfen_rag 2>&1 >&2 || true rollback exit 1 fi # Kapı 3 — OPERATOR DEGISKENLERI KONTEYNERDE MI. Bu iddia olmadan # iki dosyali `--env-file` sinifi sessizce geri gelebilir: `up` ya # reddeder ya da (varsayilani olan anahtarlarda) konteyneri SESSIZCE # compose varsayilaniyla ayaga kaldirirdi -- RAG'da ikincisi # "calisiyor gibi gorunen, yanlis kitabi okuyan servis" demektir. # Iki kanal, iki iddia: # LLM_API_KEY dolu -> operator dosyasi konteynere ulasti (env_file) # BOOK_PATH == operatorunki -> operator degeri INTERPOLASYONA girdi # Deger YAZDIRILMAZ; yalniz "var ve esit" olculur. Desen `^AD=.`: # satir basi + en az bir karakter -- bos deger eslesmez. container_env=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' hezarfen_rag) eksik=0 for ad in LLM_API_KEY BOOK_PATH RAG_EMBED_PROVIDER RAG_RERANK_PROVIDER; do if ! printf '%s\n' "$container_env" | grep -qE "^${ad}=."; then echo "container env: $ad yok ya da BOS -- operator dosyasi compose'a ulasmamis" >&2 eksik=1 fi done # Saglayici SECIMI de operator kararidir: iki kanaldan biri duserse # konteyner imaj ENV varsayilanina (api) duser ve operator "yerel # sectim" sanir. (Secilen saglayici `api` iken anahtar eksikse servis # ACILISTA reddeder -- src/service/preflight.py; o halde /ready kapisi # ve istenirse `podman logs` tam nedeni gosterir.) for ad in BOOK_PATH RAG_EMBED_PROVIDER RAG_RERANK_PROVIDER; do op_val=$(sed -n "s/^${ad}=//p" "$env_file" | tail -1) [ -n "$op_val" ] || continue got_val=$(printf '%s\n' "$container_env" | sed -n "s/^${ad}=//p" | tail -1) if [ "$got_val" != "$op_val" ]; then echo "container $ad operatorunkiyle AYNI DEGIL -- operator degeri interpolasyona girmemis. (Operator dosyasinda satir-ici '#' yorumu varsa systemd de onu degerin parcasi yapar; bkz. unit notu.)" >&2 eksik=1 fi done if [ "$eksik" -ne 0 ]; then echo 'the operator env did not reach the container; rolling back' >&2 rollback exit 1 fi echo 'ok: operator degiskenleri konteynerde (LLM_API_KEY dolu, BOOK_PATH + saglayici secimi operatorunkiyle ayni)' echo 'hezarfen_rag_compose is up and ready' REMOTE - name: Verify the served service run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$PORT'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 port=$2 export XDG_RUNTIME_DIR=/run/user/$(id -u) cd -- "$deploy_path" tag=$(cat -- "$deploy_path/current_tag") image=$(podman inspect -f '{{.Config.Image}}' hezarfen_rag) case "$image" in *"$tag"*) ;; *) echo "container runs '$image', not the current tag '$tag'" >&2 exit 1 ;; esac served=$(curl -fsS "http://127.0.0.1:$port/ready") || { echo '/ready failed' >&2; exit 1; } case "$served" in *'"status":"ready"'*) ;; *) echo "/ready did not report ready: $served" >&2; exit 1 ;; esac echo "ready; image is $image" REMOTE - name: Cleaning run: rm -rf ~/.ssh