forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

main.yml626 lines, 30.2 KiBHistoryRawDownload
1# VPS deploy, compose-style, kardeş servislerle aynı şekil (hata toparlama ucuz):
2#
3# Validate — tüm modüllerin derleme kontrolü, kendi runner'ında.
4# Build and test — bağımlılıklar + `python -m pytest tests/unit -q`
5# süiti (katalog/uygulama doğrulaması dahil), sonra repo
6# Containerfile'ından imaj (ENV bloğu dağıtım
7# varsayılanlarının TEK kaynağıdır) ve imaj tarball'ı +
8# compose dosyaları koşunun artefaktı olarak yüklenir.
9# Deploy — push'ta OTOMATIK: SSH ile kapasite ön kontrolü, imajı
10# yükle, deploy sahipli stack.env'in HEZARFEN_TAG'ini
11# BU KOŞUNUN artefaktına çevir, compose.yaml + unit'i
12# kur, stack'i yeniden başlat, `/health` ve `/ready`
13# kapılarını geçir, olmazsa önceki tag'e dön. Yani yeşil
14# bir push servisi kendiliğinden günceller.
15#
16# KAPASİTE KAPISI DEĞİŞMEDİ (kullanıcı kararı 2026-09-23: yeşil push artık
17# kendiliğinden deploy eder; 2026-09-15'teki "yalnız elle" kararı kalktı).
18# Eşik hâlâ compose.yaml `x-rag-envelope` bloğundan OKUNUR — tek kaynak;
19# sayıyı buraya ikinci kez yazmak, model çağından kalma 12 GB eşiğinin
20# sessizce geri gelmesi demekti. Yetmezse deploy sayılarıyla reddeder,
21# eşiği gevşetmez. Gömme ve rerank UZAK API'de (dağıtım varsayılanı = api)
22# → yerel modeller (~4,5 GB) indirilmez; ölçülen zarf torch ~0,4 GB +
23# 0,53 GB/10k chunk = 1,1 GB (tek korpus) … 2,6 GB (3 korpus), bkz.
24# PROJECT_STATE §11.2.
25# Operatör yerel yola (RAG_EMBED_PROVIDER=local) dönerse zarf büyür ve
26# GPU'suz makinede rerank 95,9 s sürer: ürün kapısı O-05 p50 <= 6 s
27# GEÇİLMEZ — o yapılandırma için eşiği sunucuya elle yükseltmek gerekir.
28#
29# Validate ile Build and test paralel koşar; Deploy ikisi de yeşilse
30# çalışır ve BU KOŞUNUN artefaktını alır (en yeni yeşil araması değil).
31# Yeni bir push aynı ref'teki Validate/Build'i iptal eder; uçuştaki
32# Deploy'u ASLA iptal etmez (iki deploy iç içe girerse stack karışır).
33#
34# workflow_dispatch (Actions -> Run workflow, ya da
35# `gh workflow run main.yml --ref main`) süiti koşmadan en yeni yeşil
36# build'in artefaktını yeniden deploy eder. `tests: force` önce bu
37# ref'i derler ve test eder, sonra O KOŞUNUN taze artefaktını alır.
38#
39# TWO TEST PATHS — the default is the full one (same shape as hezarfen_backend):
40#
41# DEFAULT Push it and let GitHub do everything: suite, image, bundle,
42# artifact, and — when Validate and Build are both green —
43# deploy of THIS run's artifact. This is also the recovery
44# path when the local machine is unavailable.
45# SPECIAL Prove the suite on your own machine first (scripts/gate-local.sh
46# — ~32 s here). The suite currently HANGS on the runner: run
47# 35297989416 sat at 7% for 73 minutes until it was cancelled by
48# hand, so this lane is the fast one. The script prints (or, with
49# --amend, appends) a `Local-Gate: <tree> (<n> passed, <t>s)`
50# trailer; the "Decide test gate" step verifies it against
51# HEAD^{tree} and only then skips the runner suite — CI still
52# builds the image, proves it API-only, stages, uploads and
53# deploys this run's artifact.
54# A stale or copy-pasted trailer silently falls back to running
55# the suite, so the fallback costs time, never verification.
56# Opt the pre-push hook in per clone:
57# git config core.hooksPath .githooks
58#
59# Bir seferlik ön koşullar (workflow'un erişimi dışında):
60# * repo secret'ları SSH_PRIVATE_KEY / SSH_HOST / SSH_USER;
61# * sunucuda `loginctl enable-linger <user>`;
62# * sunucuda podman + bir compose sağlayıcı;
63# * operatörün ~/hezarfen_rag/hezarfen_rag.env dosyası
64# (şablon: deploy/hezarfen_rag.env.example) ve ~/hezarfen_rag/data/
65# korpusu (imgeye girmez, salt-okunur bağlanır).
66
67name: VPS deploy
68
69on:
70 push:
71 branches:
72 - main
73 # Elle yeniden deploy kapısı — yukarıdaki başlık yorumuna bakın.
74 # auto/skip: en yeni yeşil artefaktı yeniden deploy eder (süit tekrar
75 # ödenmez). force: bu ref'i önce derler ve test eder, o taze artefaktı
76 # deploy eder.
77 workflow_dispatch:
78 inputs:
79 tests:
80 description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first."
81 type: choice
82 options:
83 - auto
84 - skip
85 - force
86 default: auto
87
88# Deploy serileştirmesi işin kendisinde: yeni bir push, uçuştaki VPS değişimine
89# dokunmadan bayat Validate/Build'i iptal edebilmeli.
90
91permissions:
92 contents: read
93 # workflow_dispatch yolu `gh run list/view` ile en yeni yeşil koşuyu arar ve o
94 # koşunun artefaktini indirir; ikisi de Actions API'sidir ve YAZMA GEREKMEZ.
95 actions: read
96
97env:
98 SERVICE: hezarfen_rag_compose
99 DEPLOY_SUBDIR: hezarfen_rag
100 ENV_FILE_NAME: hezarfen_rag.env
101 # Servisin portu (imaj ENV'i ile aynı; kapı bu portu yoklar).
102 PORT: "8000"
103 # Kapı bütçesi: `/ready` boru hattının kurulmasını bekler. API sağlayıcı
104 # yolunda (dağıtım varsayılanı) model İNDİRİLMEZ; korpus kurulumu uzak gömme
105 # çağrılarıyla saniyeler sürer. Bütçe yine cömert: operatör `local` seçerse
106 # soğuk model volume'u GB'larca indirir (ölçüldü: ~4,5 GB).
107 READY_TIMEOUT: "900"
108
109jobs:
110 validate:
111 name: Validate
112 if: github.event_name == 'push'
113 runs-on: ubuntu-24.04
114 concurrency:
115 group: ci-${{ github.workflow }}-${{ github.ref }}-validate
116 cancel-in-progress: true
117 steps:
118 - name: Checkout
119 uses: actions/checkout@v4
120 - name: Set up Python
121 uses: actions/setup-python@v5
122 with:
123 # Containerfile ile aynı satır (python:3.11-slim).
124 python-version: "3.11"
125 - name: Compile every module
126 run: python -m compileall -q src tests
127
128 build:
129 name: Build and test
130 # Pushes always build (and, by default, test). A manual redeploy reuses the
131 # newest green artifact instead of paying the suite again, unless the
132 # dispatch asks for `tests: force`, which builds and tests this ref.
133 if: github.event_name == 'push' || github.event.inputs.tests == 'force'
134 runs-on: ubuntu-24.04
135 concurrency:
136 group: ci-${{ github.workflow }}-${{ github.ref }}-build
137 cancel-in-progress: true
138 steps:
139 - name: Checkout
140 uses: actions/checkout@v4
141 - name: Set up Python
142 uses: actions/setup-python@v5
143 with:
144 python-version: "3.11"
145 # ── Which test path this run takes ──────────────────────────────────
146 # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was
147 # already through the suite on the developer's machine
148 # (scripts/gate-local.sh prints it; --amend appends it), so this run
149 # only builds, packs and uploads.
150 # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so
151 # a stale or copy-pasted trailer silently falls back to running the
152 # suite. The log always says which branch was taken, and why.
153 # Trailer shape: `Local-Gate: <40-hex tree> (<n> passed, <t>s)`.
154 - name: Decide test gate
155 id: gate
156 run: |
157 set -euo pipefail
158 # Only reaches here on a push, or a dispatch with tests=force (the
159 # job-level `if` skips the other dispatch modes) — and force means
160 # the caller explicitly asked for the suite.
161 mode='${{ github.event.inputs.tests }}'
162 tree=$(git rev-parse HEAD^{tree})
163 if [ "$mode" = force ]; then
164 echo "workflow_dispatch tests=force ⇒ running the suite on this ref"
165 echo "skip=false" >> "$GITHUB_OUTPUT"
166 exit 0
167 fi
168 claim=$(git log -1 --format=%B \
169 | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \
170 | tail -1)
171 if [ -z "$claim" ]; then
172 echo "no Local-Gate trailer on $(git rev-parse --short HEAD) ⇒ running the suite (the default path)"
173 echo "skip=false" >> "$GITHUB_OUTPUT"
174 elif [ "${claim%%|*}" != "$tree" ]; then
175 echo "local gate claims tree ${claim%%|*}; actual tree $tree ⇒ running tests anyway"
176 echo "skip=false" >> "$GITHUB_OUTPUT"
177 else
178 echo "local gate trailer matches tree $tree ⇒ skipping the suite (${claim#*|})"
179 echo "skip=true" >> "$GITHUB_OUTPUT"
180 fi
181
182 # CPU tekerleği: CI'da GPU yok ve GPU imajı ~2,5 GB daha büyük.
183 # Testler ÜÇ listeyi de ister: servis yolu (requirements.txt), yerel model
184 # yığını (requirements-local.txt) ve eval (requirements-eval.txt — yalnız
185 # CI/geliştirme; imaja girmez).
186 # The runner's pip environment exists ONLY to run the suite: the image
187 # builds its dependencies inside the Containerfile, and the API-only
188 # proof runs them inside the image. Skipped when the local gate already
189 # proved the suite.
190 - name: Install dependencies (CPU torch)
191 if: steps.gate.outputs.skip != 'true'
192 run: |
193 set -euo pipefail
194 pip install --no-cache-dir "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu
195 pip install --no-cache-dir --requirement requirements.txt \
196 --requirement requirements-local.txt \
197 --requirement requirements-eval.txt
198
199 # Bozuk bir build sunucuya ASLA ulaşmamalı: ölçüm kapıları ve regresyon
200 # süiti burada koşar. Ortam gerektiren testler (korpus, OCR dil verisi,
201 # model indirmesi) KENDİLERİ atlar ve nedenini yazar; ağır
202 # integration/e2e koşumları model indirdiği için CI kapısı DEĞİLDİR —
203 # bkz. README "CI deploy".
204 # `timeout --foreground 600` (10 min) bounds the step at the shell level,
205 # unbuffered and unpiped: what pytest printed up to the kill survives.
206 # 600 s is measured, not guessed — every green run's Test step took 41 s
207 # (35248848296, 35246056805, 35235114053, `pip install pytest` included),
208 # so this is ~15x the worst green, and it turns a stall from the hours it
209 # has actually burned (73 min stuck at 7% on 35297989416, 3 h 20 min on
210 # 35283445041) into ten minutes. `-u` is what keeps the progress line
211 # flowing into the log while the suite runs.
212 # faulthandler is the layer that NAMES the hang: after 120 s inside a
213 # single test (4x this machine's whole-suite 32 s, 3x the whole green CI
214 # step) it dumps every thread's traceback and exits 1. Core pytest, so no
215 # extra install and no plugin that could change the suite's semantics.
216 - name: Test
217 if: steps.gate.outputs.skip != 'true'
218 run: |
219 set -euo pipefail
220 pip install --no-cache-dir pytest
221 timeout --foreground 600 \
222 python -u -m pytest tests/unit -q \
223 -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True
224
225 # Always *within the test path*, including when the step above was
226 # killed: the discriminator. Disk or memory starvation shows here; a
227 # pytest process still standing after `timeout` returns is the signature
228 # of a kill the kernel could not deliver.
229 - name: Stall diagnostics
230 if: always() && steps.gate.outputs.skip != 'true'
231 run: |
232 echo '=== df -h / ==='; df -h / || true
233 echo '=== free -m ==='; free -m || true
234 echo '=== nproc ==='; nproc || true
235 echo '=== surviving pytest processes ==='
236 ps -eo pid,etimes,stat,cmd | grep '[p]ytest' || echo none
237
238 # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o
239 # gönderilir, ayrı bir CI ikizi yok.
240 - name: Build the image
241 run: |
242 set -euo pipefail
243 docker build -f Containerfile -t localhost/hezarfen_rag:$GITHUB_SHA .
244
245 # VARSAYILAN İMGE KÜÇÜK MÜ (kullanıcı kararı 2026-09-17): yerel yığın
246 # (torch/FlagEmbedding/ağırlıklar) İMAĞA GİRMEZ; yerel yol bir EKLENTİ
247 # VOLUME'u ile açılır (deploy/provision_local_stack.sh). Bu iddialar
248 # imajın kendisinde ölçülür (runner'da torch KURULU, yani runner'da
249 # ölçmek yanıltıcı olurdu).
250 # Every assertion here is an EXIT CODE or a CAPTURED STRING, never a
251 # pipeline's status: a refusal is *supposed* to exit non-zero
252 # (src/service/preflight.py -> `return 2` / `SystemExit(2)`), so the old
253 # `docker run … 2>&1 | grep -q …` under `set -o pipefail` handed that 2
254 # back as the STEP's own status and killed a check that had actually
255 # passed (job 35303767476, exit 2, with the expected line in the log).
256 # Capturing first keeps the two facts separable — the message is asserted
257 # on $local_out, the code on $local_rc.
258 - name: Prove the default image is API-only and refuses `local` cleanly
259 run: |
260 set -euo pipefail
261 img=localhost/hezarfen_rag:$GITHUB_SHA
262 # 1. torch must be ABSENT inside the image: `python -c` exits 1 when it
263 # is present, and that non-zero code IS the assertion.
264 docker run --rm "$img" python -c "import importlib.util, sys; sys.exit(1 if importlib.util.find_spec('torch') else 0)"
265 common=(--env RAG_ALLOW_UNCALIBRATED_ABSTAIN=1 --env LLM_API_KEY=ci)
266
267 # 2. the shipped default (api) must come up green: exit 0 is the assertion.
268 docker run --rm "${common[@]}" \
269 --env RAG_EMBED_PROVIDER=api --env RAG_EMBED_API_BASE=https://ornek/v1 \
270 --env RAG_EMBED_MODEL=m --env RAG_EMBED_API_KEY=k \
271 --env RAG_RERANK_PROVIDER=api --env RAG_RERANK_API_URL=https://ornek/rerank \
272 --env RAG_RERANK_MODEL=m --env RAG_RERANK_API_KEY=k \
273 "$img" python -m src.service.preflight
274
275 # 3. `local` must REFUSE — asserted twice, and neither assertion can be
276 # fooled by the other: the code must be non-zero, the message must
277 # name the provisioning script.
278 local_env=(--env RAG_EMBED_PROVIDER=local --env RAG_RERANK_PROVIDER=local)
279 local_rc=0
280 local_out=$(docker run --rm "${common[@]}" "${local_env[@]}" "$img" \
281 python -m src.service.preflight 2>&1) || local_rc=$?
282 printf '%s\n' "$local_out"
283 if [ "$local_rc" -eq 0 ]; then
284 echo "local secimi kucuk imgede GECMEMELIYDI (exit 0)" >&2
285 exit 1
286 fi
287 if ! printf '%s\n' "$local_out" | grep -q 'provision_local_stack.sh'; then
288 echo "ret metni saglama betigini adiyla soylemiyor (exit $local_rc)" >&2
289 exit 1
290 fi
291 echo "kucuk imge dogrulandi: torch yok; api yolu yesil; local yolu exit $local_rc ile ret + ret metni saglama betigini adiyla soyluyor"
292
293 - name: Stage the release bundle
294 run: |
295 set -euo pipefail
296 mkdir -p stage
297 docker save localhost/hezarfen_rag:$GITHUB_SHA | gzip > stage/hezarfen_rag.tar.gz
298 cp compose.yaml deploy/hezarfen_rag_compose.service stage/
299 echo -n "$GITHUB_SHA" > stage/tag
300 test -f stage/hezarfen_rag.tar.gz
301 test -f stage/compose.yaml
302 test -f stage/hezarfen_rag_compose.service
303 test -f stage/tag
304 ls -lh stage
305
306 - name: Upload the release
307 uses: actions/upload-artifact@v4
308 with:
309 name: release
310 path: stage
311 retention-days: 30
312
313 deploy:
314 name: Deploy
315 needs: [validate, build]
316 concurrency:
317 group: deploy
318 cancel-in-progress: false
319 # Push: yalnız validate VE build yeşilse — ikisi de sunucuyu kapılar;
320 # artefakt BU KOŞUNUNKİDİR (aşağıda needs.build.result == success).
321 # Dispatch: mevcut yol. auto/skip iki CI işini atlar ve en yeni yeşil
322 # build'i alır; tests=force build'i koşar ve bu koşunun artefaktını
323 # alır. `always()` atlamanın kapıdan geçmesini engeller.
324 if: >-
325 always() &&
326 ((needs.validate.result == 'success' && needs.build.result == 'success') ||
327 (github.event_name == 'workflow_dispatch' &&
328 (needs.validate.result == 'skipped' || needs.validate.result == 'success') &&
329 (needs.build.result == 'skipped' || needs.build.result == 'success')))
330 runs-on: ubuntu-24.04
331 steps:
332 # Dispatch ve bu koşuda build YOKSA (auto/skip): BUILD işi yeşil olan
333 # en yeni push koşusunu alır. Push ve tests=force buraya düşmez —
334 # onların artefaktı aşağıdaki adımdır.
335 - name: Find the newest green build
336 if: needs.build.result == 'skipped'
337 env:
338 GH_TOKEN: ${{ github.token }}
339 run: |
340 set -euo pipefail
341 run_id=""
342 for rid in $(gh run list -R "$GITHUB_REPOSITORY" --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do
343 if [ "$(gh run view -R "$GITHUB_REPOSITORY" "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then
344 run_id=$rid
345 break
346 fi
347 done
348 if [ -z "$run_id" ]; then
349 echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2
350 exit 1
351 fi
352 echo "deploying the release from run $run_id"
353 echo "run_id=$run_id" >> "$GITHUB_ENV"
354
355 - name: Fetch the green release
356 if: needs.build.result == 'skipped'
357 uses: actions/download-artifact@v4
358 with:
359 name: release
360 path: stage
361 run-id: ${{ env.run_id }}
362 github-token: ${{ github.token }}
363
364 # Push, ve tests=force: artefakt bu koşunun kendisinin ürettiği sürüm.
365 - name: Fetch this run's release
366 if: needs.build.result == 'success'
367 uses: actions/download-artifact@v4
368 with:
369 name: release
370 path: stage
371
372 - name: Check the release is complete
373 run: |
374 set -euo pipefail
375 test -f stage/hezarfen_rag.tar.gz
376 test -f stage/compose.yaml
377 test -f stage/hezarfen_rag_compose.service
378 test -f stage/tag
379
380 - name: Install SSH keys
381 run: |
382 mkdir -p ~/.ssh
383 echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
384 ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts
385
386 - name: Upload the release
387 run: |
388 set -euo pipefail
389 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
390 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
391 set -euo pipefail
392 case "$1" in
393 ''|/*|*..*)
394 echo "Refusing a broad deploy subdirectory: '$1'" >&2
395 exit 1
396 ;;
397 esac
398 deploy_path=$HOME/$1
399 mkdir -p -- "$deploy_path"
400 REMOTE
401 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'"
402
403 - name: Load the image and restart the service
404 run: |
405 set -euo pipefail
406 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
407 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME' '$PORT' '$READY_TIMEOUT'" <<'REMOTE'
408 set -euo pipefail
409 deploy_path=$HOME/$1
410 service=$2
411 env_file=$deploy_path/$3
412 port=$4
413 ready_timeout=$5
414 export XDG_RUNTIME_DIR=/run/user/$(id -u)
415 cd -- "$deploy_path"
416
417 if [ ! -f "$env_file" ]; then
418 echo "missing $env_file — create it (0600) from the repo's deploy/hezarfen_rag.env.example" >&2
419 exit 1
420 fi
421 chmod 0600 -- "$env_file"
422
423 # OPERATOR ORTAMI SURECE ALINIR. podman-compose interpolasyonu ORTAM
424 # DEGISKENLERINE bakar ve `--env-file` YALNIZ SON dosyayi cozer
425 # (podman_compose.py:2941-2946, :2559): iki dosyali cagri operator
426 # dosyasini tamamen dusuruyordu. RAG'da bu "required variable ...
427 # is missing" DEGIL, SESSIZ bir yanlis-korpus olarak gorunurdu:
428 # compose.yaml'daki BOOK_PATH/SINIF/DERS interpolasyonu cihaz
429 # varsayilanina (10/biyoloji) duser ve `environment:` env_file'i
430 # ezdigi icin konteyner operatorun kitabini HIC gormez. Bu yuzden
431 # dosya satir satir okunur -- kabuk genisletmesi YOK (deger icindeki
432 # `$` oldugu gibi kalir), systemd `EnvironmentFile=` ile AYNI
433 # davranis (satir-ici `#` korunur; bkz. unit notu).
434 while IFS= read -r satir || [ -n "$satir" ]; do
435 case "$satir" in ''|'#'*) continue ;; esac
436 anahtar=${satir%%=*}
437 deger=${satir#*=}
438 case "$anahtar" in
439 ''|*[!A-Za-z0-9_]*)
440 echo "operator env: gecersiz anahtar adi -- harf/rakam/alt cizgi beklenirdi" >&2
441 exit 1
442 ;;
443 esac
444 export "$anahtar=$deger"
445 done < "$env_file"
446
447 # KAPASİTE ÖN KONTROLÜ — EŞİKLER TEK KAYNAKTAN: compose.yaml'daki
448 # `x-rag-envelope`. Ölçülmüş zarf (API sağlayıcı yolu): torch ~0,4 GB
449 # + 0,53 GB/10k chunk = 1,1 GB (tek korpus) … 2,6 GB (3 korpus);
450 # mem_limit_mb aynı zamanda host RAM eşiğidir (kap tavanına kadar
451 # çıkabilmeli). Diskte imaj + rollback için ÖNCEKİ imaj da durur.
452 # Blok okunamazsa kapı ölçülemez: sessizce devam etmek yerine reddet.
453 envelope_kaynak="compose.yaml"
454 mem_limit_mb=$(awk '/^x-rag-envelope:/{f=1} f&&/^[[:space:]]+mem_limit_mb:/{print $2; exit}' "$envelope_kaynak")
455 disk_min_gb=$(awk '/^x-rag-envelope:/{f=1} f&&/^[[:space:]]+disk_min_gb:/{print $2; exit}' "$envelope_kaynak")
456 case "${mem_limit_mb}:${disk_min_gb}" in
457 *[!0-9:]*|:*|*:)
458 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
459 exit 1
460 ;;
461 esac
462 avail_mb=$(awk '/MemAvailable/ {print int($2/1024)}' /proc/meminfo)
463 disk_gb=$(df -BG --output=avail "$deploy_path" | tail -1 | tr -dc '0-9')
464 if [ "$avail_mb" -lt "$mem_limit_mb" ] || [ "$disk_gb" -lt "$disk_min_gb" ]; then
465 echo "refusing to deploy: ${avail_mb} MB RAM available (need >= ${mem_limit_mb}) and ${disk_gb} GB disk (need >= ${disk_min_gb})." >&2
466 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
467 exit 1
468 fi
469
470 command -v podman >/dev/null || {
471 echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2
472 exit 1
473 }
474 podman compose version >/dev/null 2>&1 || {
475 echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2
476 exit 1
477 }
478
479 gunzip -c "$deploy_path/hezarfen_rag.tar.gz" | podman load
480 tag=$(cat -- "$deploy_path/tag")
481
482 if [ -f "$deploy_path/current_tag" ]; then
483 cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag"
484 fi
485 printf '%s\n' "$tag" > "$deploy_path/current_tag"
486
487 # stack.env deploy sahipli (operatorun ayar dosyasindan farkli):
488 # yalniz imaj tag'ini tasir ve compose'a giden TEK `--env-file` odur
489 # -- operator degerleri yukarida surece alindi (EnvironmentFile= ile
490 # ayni iki-kanal deseni). Iki dosyali cagri bu saglayicida operator
491 # dosyasini dusurur (podman_compose.py:2941-2946, :2559); ortam
492 # degiskeni --env-file degerlerini ezer (:2562).
493 printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env"
494
495 chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_rag_compose.service"
496 rm -f -- "$deploy_path/hezarfen_rag.tar.gz"
497
498 compose_up() {
499 podman compose --profile product --env-file "$deploy_path/stack.env" up -d --no-build
500 }
501 rollback() {
502 if [ -f "$deploy_path/previous_tag" ]; then
503 prev=$(cat -- "$deploy_path/previous_tag")
504 printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env"
505 printf '%s\n' "$prev" > "$deploy_path/current_tag"
506 compose_up
507 echo "rolled back to $prev" >&2
508 else
509 # İlk deploy: geri dönülecek imaj yok. `-v` YOK — model cache ve
510 # maliyet defteri volume'ları korunur.
511 podman compose --profile product --env-file "$deploy_path/stack.env" down
512 echo 'first deploy failed; stack stopped, volumes kept' >&2
513 fi
514 }
515
516 mkdir -p -- "$HOME/.config/systemd/user"
517 install -m 0644 -- "$deploy_path/hezarfen_rag_compose.service" "$HOME/.config/systemd/user/$service.service"
518 systemctl --user daemon-reload
519 systemctl --user enable -- "$service"
520 systemctl --user restart "$service" || true
521
522 # Kapı 1 — liveness: süreç ayağa kalktı mı (boru hattı arkada kurulur).
523 live_ok=0
524 for _ in $(seq 1 60); do
525 served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || true
526 case "$served" in
527 *'"status":"ok"'*) live_ok=1; break ;;
528 esac
529 sleep 1
530 done
531 if [ "$live_ok" -ne 1 ]; then
532 echo '/health never answered ok; rolling back' >&2
533 podman logs --tail 30 hezarfen_rag 2>&1 >&2 || true
534 rollback
535 exit 1
536 fi
537
538 # Kapı 2 — readiness: boru hattı GERÇEKTEN kuruldu mu (#50: `/health`
539 # servis bozukken de ok döner). Soğuk model volume'unda bu adım
540 # indirmeleri bekler; bütçe READY_TIMEOUT saniyedir.
541 ready_ok=0
542 for _ in $(seq 1 "$ready_timeout"); do
543 served=$(curl -fsS "http://127.0.0.1:$port/ready" 2>/dev/null) || true
544 case "$served" in
545 *'"status":"ready"'*) ready_ok=1; break ;;
546 esac
547 sleep 1
548 done
549 if [ "$ready_ok" -ne 1 ]; then
550 echo "/ready never became ready within ${ready_timeout}s; rolling back" >&2
551 curl -sS "http://127.0.0.1:$port/ready" >&2 || true
552 podman logs --tail 30 hezarfen_rag 2>&1 >&2 || true
553 rollback
554 exit 1
555 fi
556
557 # Kapı 3 — OPERATOR DEGISKENLERI KONTEYNERDE MI. Bu iddia olmadan
558 # iki dosyali `--env-file` sinifi sessizce geri gelebilir: `up` ya
559 # reddeder ya da (varsayilani olan anahtarlarda) konteyneri SESSIZCE
560 # compose varsayilaniyla ayaga kaldirirdi -- RAG'da ikincisi
561 # "calisiyor gibi gorunen, yanlis kitabi okuyan servis" demektir.
562 # Iki kanal, iki iddia:
563 # LLM_API_KEY dolu -> operator dosyasi konteynere ulasti (env_file)
564 # BOOK_PATH == operatorunki -> operator degeri INTERPOLASYONA girdi
565 # Deger YAZDIRILMAZ; yalniz "var ve esit" olculur. Desen `^AD=.`:
566 # satir basi + en az bir karakter -- bos deger eslesmez.
567 container_env=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' hezarfen_rag)
568 eksik=0
569 for ad in LLM_API_KEY BOOK_PATH RAG_EMBED_PROVIDER RAG_RERANK_PROVIDER; do
570 if ! printf '%s\n' "$container_env" | grep -qE "^${ad}=."; then
571 echo "container env: $ad yok ya da BOS -- operator dosyasi compose'a ulasmamis" >&2
572 eksik=1
573 fi
574 done
575 # Saglayici SECIMI de operator kararidir: iki kanaldan biri duserse
576 # konteyner imaj ENV varsayilanina (api) duser ve operator "yerel
577 # sectim" sanir. (Secilen saglayici `api` iken anahtar eksikse servis
578 # ACILISTA reddeder -- src/service/preflight.py; o halde /ready kapisi
579 # ve istenirse `podman logs` tam nedeni gosterir.)
580 for ad in BOOK_PATH RAG_EMBED_PROVIDER RAG_RERANK_PROVIDER; do
581 op_val=$(sed -n "s/^${ad}=//p" "$env_file" | tail -1)
582 [ -n "$op_val" ] || continue
583 got_val=$(printf '%s\n' "$container_env" | sed -n "s/^${ad}=//p" | tail -1)
584 if [ "$got_val" != "$op_val" ]; then
585 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
586 eksik=1
587 fi
588 done
589 if [ "$eksik" -ne 0 ]; then
590 echo 'the operator env did not reach the container; rolling back' >&2
591 rollback
592 exit 1
593 fi
594 echo 'ok: operator degiskenleri konteynerde (LLM_API_KEY dolu, BOOK_PATH + saglayici secimi operatorunkiyle ayni)'
595 echo 'hezarfen_rag_compose is up and ready'
596 REMOTE
597
598 - name: Verify the served service
599 run: |
600 set -euo pipefail
601 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
602 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$PORT'" <<'REMOTE'
603 set -euo pipefail
604 deploy_path=$HOME/$1
605 port=$2
606 export XDG_RUNTIME_DIR=/run/user/$(id -u)
607 cd -- "$deploy_path"
608 tag=$(cat -- "$deploy_path/current_tag")
609 image=$(podman inspect -f '{{.Config.Image}}' hezarfen_rag)
610 case "$image" in
611 *"$tag"*) ;;
612 *)
613 echo "container runs '$image', not the current tag '$tag'" >&2
614 exit 1
615 ;;
616 esac
617 served=$(curl -fsS "http://127.0.0.1:$port/ready") || { echo '/ready failed' >&2; exit 1; }
618 case "$served" in
619 *'"status":"ready"'*) ;;
620 *) echo "/ready did not report ready: $served" >&2; exit 1 ;;
621 esac
622 echo "ready; image is $image"
623 REMOTE
624
625 - name: Cleaning
626 run: rm -rf ~/.ssh