The worker payload is now a read-only squashfs rootfs carried INSIDE the
initramfs (build/alpine-worker/build-squashfs.sh), so the guest needs no
disk and no root UUID.
boot.ipxe therefore loads vmlinuz-virt + initramfs-virt over HTTP and
boots them; the initramfs attaches the embedded squashfs read-only and
switch_roots into the worker system.
This drops iPXE's SAN-boot extension from the production chain - the
dependency behind T14 (the 6.18.57 PCI-match regression) and risk R1
(SAN under ESXi EFI, never verified). The disk profile and its sanboot
chain stay reachable through boot-bypass.ipxe as the legacy path.
bootMode=pxe already attached no disk (vm.nix), so no change there.
В v2 без явного выбора CLI берёт модель из реестра сам
(opencode/minimax-m3.1-flash-free) и передаёт её явно — она перебивает
модель агента, заданную oh-my-opencode-slim. Проверено по сообщению в БД:
без фикса запрос шёл на бесплатной модели. Рабочая машина обходится за счёт
«помни последний использованный» в TUI, серверная БД пустая.
The comment said 'A latest/ symlink points at the newest <rev>'. Since
T18 the worker deploy publishes into a real latest/ directory with a
rename(2); the symlink scheme was measured to be non-atomic (GNU
mv -T on a symlink-to-directory copies instead of renaming). The
iPXE scripts address the path, not the object type, so nothing in the
behaviour changes - only the description.
Mirrors the change in pxe-infra-automation (T19). The bypass chain
loaded the kernel and the initramfs over HTTP and then failed with
"mounting /dev/ram0 on /sysroot failed" - the root filesystem is the
worker's ext4 partition, addressed by UUID, and the script pointed at a
device that does not exist. The disk was visible the whole time
(virtio_blk virtio1: [vda] 2097152); only the command line was wrong.
Now the script fetches the root UUID from the HTTP root with isset and
puts it on the kernel command line, matching the options the
systemd-boot entry uses. The image must be attached to the guest as a
local block device (EXTRA_DRIVES in direct mode); the rootfs is not
inside the initramfs.
This path does not use iPXE's sanboot, so it works on firmware without
INT13 SAN extensions - which is what makes the ESXi rig usable
regardless of risk R1.
The production chain (boot.ipxe, sanboot) is unchanged; this script is
only reached when pxe-infra.bootloader.bypassFallback.enable is set.
The UUID is published next to the image by the pxe-infra-automation
deploy script, and is written without a trailing newline because iPXE
copies the file's contents into a variable verbatim.
Not verified on hardware: the artifact has not been republished since
the change.
Раннер на sapphira отдаёт job'у PATH, равный своему hostPackages, и он
фиксируется в systemd-юните при активации -- чтобы добавить туда инструмент,
нужен nixos-rebuild switch на хосте. Для workflow'ов в oqyude/winos это тупик:
jq (scripts/update-manifest.sh) и pwsh (scripts/update-kvrt.ps1) в наборе
раннера отсутствуют, а nix-shell -p не запасной путь -- реестр nix на sapphira
пустой, каналов нет, -p не находит nixpkgs.
Что сделано:
- lib/ci-tools.nix -- один список инструментов CI.
- devshells/default.nix: devshell `ci` (nix develop .#ci) с этим списком.
Workflow может взять PATH devshell'а и получить jq/pwsh без пересборки:
nix develop /etc/nixos#ci --command bash -c 'echo $PATH'
- modules/server/gitea-runner.nix: hostPackages берёт тот же список, чтобы
набор раннера и devshell не расходились; в списке теперь ещё и powershell.
Проверка: devshell собирается на sapphira (nix develop /etc/nixos#ci) и
отдаёт jq и pwsh.
PATH of a host-mode job is exactly this list (nixos upstream module: path = coreutils ++ optionals wantsHost instance.hostPackages), so a tool that is not listed here simply does not exist for the job.
scripts/update-manifest.sh in oqyude/winos hard-requires jq -- 'for dep in curl jq' -- and calls it 14 times. It is a vendored script (logic preserved verbatim from Dicklesworthstone/scoop-bucket), so the tool belongs here rather than being rewritten out of the script.
Effect: the bucket auto-update workflow in oqyude/winos can actually apply the manifest updates it detects. Without jq it failed at 'required tool not found: jq' and every update was skipped.
Requires a rebuild on sapphira to take effect: the runner's systemd unit gets its PATH from hostPackages at activation time.
T-FIX-BADZIP (round 2): POST /api/match возвращал nginx-HTML 500 даже после фикса бэкенда, потому что:
- nginx auth_request по умолчанию шлёт sub-request с методом parent'а (POST для upload);
- В /authelia location не было `proxy_pass_request_body off` и `Content-Length ""`;
- nginx пересылал Content-Length в sub-request к Authelia, но не само тело;
- Authelia ждала обещанные байты и отвечала 408 (Request Timeout);
- nginx auth_request не классифицирует 408 как 2xx/4xx и возвращал клиенту 500.
vtimeline.zeroq.su уже починил этот же баг (vtimeline.nix + комментарий в nginx.conf) — engipy-frontend.nix просто забыл скопировать паттерн. Копирую.
Refs: T-FIX-BADZIP (production bug: HTTP 500 при загрузке xlsx через nginx/Authelia)
После миграции на ONNX runtime старая path через nix-store
gcc-lib + openblas больше не нужна и вредит:
1. nix-store libstdc++ + openblas конфликтовали с torch-internal
OpenMP при SBERT forward (RuntimeError: could not create a
primitive в GELU activation) — ранее приходилось ставить
OMP_NUM_THREADS=1 чтобы torch не пытался multi-thread.
2. После ONNX-миграции wheel-installed onnxruntime и numpy
приносят свои bundled deps; тянуть ещё openblas поверх не нужно.
Системный nix-ld overrides directory (NixOS) лежит в фиксированном
пути /run/current-system/sw/share/nix-ld/lib и содержит симлинки
на 64-bit libstdc++.so.6, libz.so.1, libdl.so.2, libgcc_s.so.1,
libpthread.so.0, libc.so.6. Этого достаточно для wheels, и не
конфликтует с onnxruntime (тот поставляет свои OpenMP-библиотеки
внутри wheel).
Сабж: оставляю OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1,
TOKENIZERS_PARALLELISM=false. Убираю MKL_NUM_THREADS — onnxruntime
не использует MKL.
Проверено: через этот LD_LIBRARY_PATH numpy импортируется в
/var/lib/engipy/venv/bin/python на rydiwo, а ONNX inference
embed_gesn.py через ORTModelForFeatureExtraction
проходит (shape=(2,312) time=0.00s).
Без LD_LIBRARY_PATH numpy падает 'Error importing numpy: you should
not try to import numpy from its source directory' (не находит
свой wheel-installed openblas без переменной). Возвращаю
LD_LIBRARY_PATH, но добавляю OMP_NUM_THREADS=1 MKL_NUM_THREADS=1
OPENBLAS_NUM_THREADS=1 и TOKENIZERS_PARALLELISM=false — это
отключает multi-thread BLAS, где SBERT forward падал в 'could
not create a primitive'. Inference пойдёт медленнее (~5 сек),
но не упадёт.
При POST /api/match SBERT forward pass через torch CPU падает с
RuntimeError: could not create a primitive на
transformers/activations.py:78 (GELU activation через BLAS).
Воспроизводимо на rydiwo с тем же Python/torch/openblas,
что работает локально.
Корневая причина — openblas lib из nix-store конфликтует с torch
internal threading. Переменная LD_LIBRARY_PATH=/nix/store/.../openblas/lib
+ libgcc.cc.cc.lib пробрасывалась мной как 'safety net' для других
wheel'ов (uvloop/scipy используют BLAS), но для torch это создаёт
конфликт (torch тащит свой mkl/openblas).
Без override torch берёт системный /lib/x86_64-linux-gnu/libgomp
и /lib/.../libopenblas (если установлен на системе). Если нет —
просто без OpenMP threading. SBERT inference должен идти медленнее
(без multi-thread MKL), но не падать.
Если после теста SBERT всё ещё падает — следующий вариант:
fastembed (ONNX-based, без torch) или optimum[onnx].
В app/main.py нет module-level 'app' — только create_app() функция-
фабрика (создаёт экземпляр FastAPI на каждый запуск). Без --factory
uvicorn ждёт 'app.main:app' (атрибут 'app' в модуле), не находит
его и завершается 'Attribute app not found in module app.main'.
smoke_api.sh в проекте использует именно '--factory app.main:create_app',
это рабочий паттерн для engipy — перенёс в systemd ExecStart.
FastAPI route /api/match использует file: UploadFile = File(...). При
импорте app.routes.match (через 'import app.main') FastAPI вызывает
ensure_multipart_is_installed() и падает с RuntimeError, если
python-multipart не установлен. Добавил в requirements.txt.
1. structlog==24.4.0 — app/main.py импортирует его на boot, иначе
ModuleNotFoundError стартует uvicorn. Аналогично pandas и
openpyxl — app.matchers и app.routes.match их используют, и
'import app.main' тянет всю иерархию.
2. PYTHONPATH=${cfg.dataDir} — WorkingDirectory не добавляет cwd в
sys.path автоматически, uvicorn не находит 'app.main:app' при
запуске из /var/lib/engipy. PYTHONPATH — это путь, который uvicorn
ищет при import_from_string.
Предыдущий подход ставил torch отдельным pip install -r torchReqs
ПОСЛЕ установки sentence-transformers. Но sentence-transformers
(через transformers/torch>=1.11.0) уже резолвил universal-torch
с PyPI при первой установке — это тянуло cuda-toolkit ~3GB.
Исправлено: torch==2.6.0+cpu + --extra-index-url pytorch.org/whl/cpu
включены прямо в requirements.txt. Sentence-transformers увидит
torch==2.6.0+cpu как явное ограничение и возьмёт именно CPU-wheel
(он единственный с +cpu тэгом, PyPI не предлагает).
pkgs.fetchPypi + python311.withPackages / buildEnv.override не
раскладывают wheels в site-packages — итоговый env содержит только
4 базовых файла python311 (__pycache__, README.txt, sitecustomize.py,
_sysconfigdata__). engipy.service стартует с 'No module named uvicorn'.
Перешёл на прямое pip install в systemd ExecStartPre:
* engipy-install.service (oneshot) — создаёт /var/lib/engipy/venv,
pip install -r requirements.txt, pip install torch (--index-url
pytorch.org/whl/cpu). Маркер .engipy-venv-installed после успеха.
* engipy.service (simple, requires engipy-install) — uvicorn из
созданного venv.
Wheel'ы остаются те же (16 штук, ~1.7 GB на диске после распаковки),
но Nix больше не пытается интегрировать их в buildEnv — pip делает
это прямым образом за ~2-3 мин на rydiwo. Никаких часовых компиляций.
torch по-прежнему 2.6.0+cpu с https://download.pytorch.org/whl/cpu
(~250 MB). SBERT-модель 'cointegrated/rubert-tiny2' кэшируется при
первом запросе в cfg.dataDir/.cache/huggingface/ (~50 MB).
python311.buildEnv уже derivation, не функция (правый attrset, не
lambda), поэтому python311.buildEnv { ... } падает с 'attempt to
call something which is not a function'. Аналогично pkgs.fetchPip
не существует — есть pkgs.fetchPypi (с 'y').
Исправлено:
* requirements.nix: pkgs.fetchPip → pkgs.fetchPypi
* engipy-backend.nix default: pkgs.python311.buildEnv →
pkgs.python311.withPackages (ps: ...)
Сгенерировано в WSL nixos и подтверждено: 'nix-build' успешно
собирает /nix/store/...-python3-3.11.17-env (около 17 symlinks).
В description для option dataDir было ${dataDir} — Nix
внутри ''-строки интерпретирует как переменную, не как литерал.
Поскольку dataDir объявлена самой опцией ниже (mutually-
recursive через cfg.dataDir это и есть сама опция), Nix ругался
'undefined variable dataDir'. Исправлено на `$dataDir/web` в
бэктиках.
Sapphira (2 cores, 5.6 GB RAM) не вытянет torch/sentence-transformers —
первый nixos-rebuild на ней упал с No space left on device и долгим
копированием 50+ MB ML-deps с узкого cache.nixos.org канала. Разносим
архитектуру:
* engipy-frontend.nix (sapphira) — только nginx vhost engipy.zeroq.su.
/api/* → proxyPass на 192.168.1.102:8000 (rydiwo). Статика
/var/lib/engipy/web на root fs (без bind-mount, External не нужен).
Authelia forward-auth через wildcard *.zeroq.su → one_factor.
* engipy-backend.nix (rydiwo) — systemd unit engipy с uvicorn +
FastAPI + полный ML-стек. bindAddress=0.0.0.0, чтобы sapphira
могла проксировать по LAN. Sandbox через PrivateTmp/ProtectSystem
+ LD_LIBRARY_PATH для libgomp/openblas (нужно torch CPU-wheel'у).
* requirements.nix — wheels с PyPI + torch 2.6.0+cpu c
https://download.pytorch.org/whl/cpu. Все sha256-хэши посчитаны
в WSL nixos через 'pip download --only-binary=:all: --platform
manylinux_2_17_x86_64' + 'nix hash path --type sha256'. Никакой
компиляции — только скачивание wheels на rydiwo (~5-10 мин rebuild).
* configurations/server.nix — host.engipy-frontend.enable = true +
backendHost = 192.168.1.102.
* configurations/mini-laptop.nix — host.engipy-backend.enable = true +
bindAddress = 0.0.0.0 + logind.lidSwitch = ignore (rydiwo
используется как headless-сервер, не засыпать при закрытии крышки).
nsot: старый engipy.nix (185 строк) удалён — он делал всё сразу на одном
хосте, что перегружало sapphira. nginx.nix vhost перенесён в
engipy-frontend.nix, чтобы не дублировать.
engipy webapp использует pkgs.python311.withPackages (fastapi, pydantic,
sentence-transformers, torch). При evaluation Nix встречает
python3.11-sphinx-9.1.0 как транзитивную docs-dep — а она не
поддерживает python 3.11 (broken). sphinx не нужен в runtime, и
реальная БД от него не зависит, поэтому глушим ошибку до warning
через nixpkgs.problems.handlers (см. .agent/rules/project-rules.md
R1 — outputs должны вычисляться).
NixOS ругался «attribute 'systemd' already defined», потому что Nix
видит systemd = storage.systemd и systemd.services.engipy = ... как
два разных присвоения корневому systemd, а не как deep-merge.
lib.mkMerge делает явный merge двух attrsets внутри systemd.
engipy.zeroq.su — FastAPI webapp для подбора ГЭСН по ВОР (uvicorn + SBERT).
Дизайн по образцу vtimeline.nix (systemd unit) + vtimeline.zeroq.su vhost:
- modules/server/engipy.nix: новый модуль. systemd-юнит engipy запускает
uvicorn на 127.0.0.1:8000 (порт через host.engipy.port). Хранилище —
через xlib.helpers.mkServiceStorage: bind-mount
/mnt/services/engipy → /var/lib/engipy (mode 0750 engipy:engipy),
соглашение R1.2 в .agent/rules/project-rules.md. Зависимость
requires = [ var-lib-engipy.mount ] заменяет нерабочий mkStorageGuard.
nginx читает /var/lib/engipy/web через users.users.nginx.extraGroups.
Опции: port, user, pythonPackage, dbFileName, embeddingsStem, model.
- modules/server/default.nix: импорт ./engipy.nix + host.engipy.enable
с pythonPackage = pkgs.python311.withPackages (fastapi/uvicorn/
pydantic/sqlalchemy/numpy/sentence-transformers/torch) — список из
nix/engipy.nix проекта, чтобы backend-стек на сервере совпадал с
dev-окружением.
- modules/server/nginx.nix: vhost engipy.zeroq.su (forceSSL + ACME).
/api/ проксирует на 127.0.0.1:8000 (client_max_body_size 50m для
крупных ВОР-файлов), / отдаёт /var/lib/engipy/web с try_files для
SPA-fallback. Authelia forward-auth через auth_request /authelia +
401→302 redirect на authelia.zeroq.su (как у vtimeline.zeroq.su) —
wildcard *.zeroq.su → one_factor уже покрывает новый vhost.
Первый nixos-rebuild на sapphira собирает torch + sentence-transformers
~30-90 мин (2 ядра); последующие пересборки берут из кэша.
The former single boot.ipxe writeText block in modules/pxe-infra/ipxe.nix has been split into two static scripts under artifacts.root/http/:
- boot.ipxe \u2014 production sanboot path. Chains to the
alpine-worker raw image; OVMF walks the ESP,
systemd-boot reads loader/entries/alpine.conf.
- boot-bypass.ipxe \u2014 H_fix.1b regression baseline. kernel+initrd
path; preserved byte-identical to the pre-split
boot.ipxe content (matches the
T10-h-fix-1b log shape on rydiwo 2026-10-14).
autoexec.ipxe now selects the chain target via a new option:
pxe-infra.bootloader.bypassFallback.enable (lib.types.bool, default false)
When true, autoexec.ipxe chains to boot-bypass.ipxe; when false (default),
to boot.ipxe. Both scripts are always staged (no mkIf gate) so the chain
target flips with a config change + rebuild, no redeploy.
In modules/pxe-infra/default.nix a new systemd-tmpfiles L+ rule mirrors
the existing boot.ipxe rule for boot-bypass.ipxe.
This unblocks H_fix.2 (real sanboot + POST end-to-end verification on
rydiwo). The bypass path is the regression baseline \u2014 S4 in
.agent/notes/H_fix.2-scenarios.md validates it still reaches the Alpine
Init shell when the option is flipped.
Authelia's forward-auth endpoint was handed the original Content-Length
header of the client request but not the body itself, so it blocked
reading bytes that never arrived and finally answered 408. auth_request
cannot classify 408, so nginx reported it to the client as 500 + an HTML
error page, and the frontend surfaced "Server returned non-JSON" on
every upload.
Every bodied POST was affected (JSON upload and zip ingest) while plain
GETs kept working, which is why the page loaded fine but uploads failed.
Payload size was irrelevant: a 60-byte body failed identically to a
300 KB one.
With `proxy_pass_request_body off` and an empty Content-Length, Authelia
authorises on the forwarded headers alone, which is all forward-auth
needs. Applied to both "= /authelia" blocks (vtimeline.zeroq.su and
tty.zeroq.su).
Verified on a reproduction bench mirroring the production vhost: bodied
POSTs went 500 (HTML, 6 s timeout) -> 201 (JSON, ~10 ms).
bun в shell PATH (home/modules/herdr-runtime.nix) не помогает — herdr-web-ui
plugin на rydiwo использует собственный runtime manager (path-pattern
~/.local/share/herdr-web-ui/install.<hash>/runtime/bin/bun, типичный bun
runtime installer), а не fallback на PATH. Этот bun динамически слинкован
для generic linux (glibc) и на NixOS без nix-ld stub падает с «NixOS cannot
run dynamically linked executables intended for generic linux environments
out of the box».
Включаю programs.nix-ld глобально (в modules/essentials) с одной зависимостью
stdenv.cc.cc.lib (glibc + libstdc++ + libgcc_s) — этого достаточно для
запуска glibc-based bun. Применяется ко всем NixOS-хостам; на хостах без
generic-linux бинарей overhead минимальный (несколько .so в /lib, плюс
ld-linux.so.2 в /libexec).
Дополнение / подноши: если конкретный плагин потребует ещё (zlib, openssl,
etc.), расширять programs.nix-ld.libraries через ldd-проверку и точечно.
Раньше # nix-ld.enable = true; в этом же файле было закомментировано —
видимо, не дошли руки; теперь разкомментировано с явным почему.
The herdr-web-ui vhost was using authelia forward-auth like every
other *.zeroq.su vhost, but the upstream Bun server's sameOrigin
check (server/machine-security.ts:18-46) is not designed for
reverse proxies other than Tailscale serve:
1. POST /api/auth through the vhost returned 500 because nginx's
auth_request subrequest returned 401 and error_page 401 =302
only works for GET. (Fixed by exempting /api/auth and
/api/devices/pair from authelia — commit 61ad57a.)
2. The sameOrigin function compares the browser's Origin against
new URL(request.url).origin. For a proxy_pass to 127.0.0.1:7317
the URL is http://127.0.0.1:7317/..., which never matches
https://herdr.zeroq.su. The function does NOT read
X-Forwarded-Host. Every cross-origin POST returned 403
invalid_origin. (Fixed by in-place patch on the plugin's
server/machine-security.ts on sapphira to also trust
X-Forwarded-Host when X-Forwarded-Proto is also set, and to
reset expected.port so the comparison matches the browser's
default-port Origin. The .orig file is saved alongside so
`cp server/machine-security.ts.orig server/machine-security.ts`
reverts the change before any `herdr plugin update`.)
3. NixOS nginx with recommendedProxySettings = true appends an
include of a file that sets Host, X-Forwarded-Proto,
X-Forwarded-Host AFTER every location's extraConfig.
My previous `proxy_set_header X-Forwarded-Host $host;` in
extraConfig ended up sending the header twice
("herdr.zeroq.su, herdr.zeroq.su"), the sameOrigin function
then sees a comma-joined value, fails to parse it as a host,
and 403s every cross-origin POST. Removing the explicit
proxy_set_header lines lets the include's single values
reach the upstream correctly.
4. Static assets (manifest.webmanifest, sw.js, favicon.ico,
/assets/*) used to go through the authelia-gated / location,
which 302-redirected them to authelia.zeroq.su, breaking the
PWA's manifest load and the service worker. Exempted via a
regex location; with the bun patch and the include-based
header set, they now load with the right Host.
The herdr.zeroq.su vhost now serves the SPA with only the
herdr_web_token gate. Authelia stays in front of every other
*.zeroq.su vhost. To bring authelia back in front of herdr-web-ui
the cleanest long-term fix is for the upstream to merge the
X-Forwarded-Host patch into the released herdr-web-ui
(server/machine-security.ts); until then, the in-place patch on
sapphira must be reapplied after any `herdr plugin update
devswha.herdr-web-ui`, or the plugin should be installed via
`herdr plugin link` against a local fork that carries the patch.
The herdr-web-ui token entry form (POST /api/auth with JSON body
{"token": "..."}) and the 6-digit pairing flow (POST /api/devices/pair)
were returning 500 through the vhost instead of 204/401. nginx's
auth_request subrequest hits authelia first; authelia returns 401
because the visitor is not signed in yet (no authelia cookie);
error_page 401 =302 then tries to redirect the original POST, but
nginx's 302 rewrite only works cleanly for GET — the POST round
trips to a 500 ("auth request unexpected status" in the nginx
error log). Same root cause as the working vtimeline/tty vhosts,
where the form is GET-only and the redirect works.
Fix: add a regex location '~ ^/api/(auth|devices/pair|health)$'
that proxies these three paths to 127.0.0.1:7317 WITHOUT the
authelia auth_request. The Bun server's own auth.ts keeps the same
three paths open in requiresAuth() (server/auth.ts:79-85), so a
missing or wrong token is rejected there with 401 + JSON body —
the gate is enforced one layer down, just not by authelia.
Verified after the rebuild:
POST /api/auth (body=token) -> 204 + set-cookie herdr_web_token
POST /api/devices/pair (code=...) -> 401 invalid_code (not 500)
GET /api/health -> 200
Real-browser flow now: visitor opens herdr.zeroq.su -> authelia
login -> web UI shows pair/token form -> submit POST /api/auth
works -> HttpOnly cookie set -> app loads.
Per-UID design of herdr (Unix sockets, no HTTP) drove the home-manager
choice over a NixOS module — mirrors the existing opencode-web pattern.
- home/modules/herdr.nix: new systemd user service running
herdr 0.9.3 on sapphira, --session herdr-prod,
EnvironmentFile from sops opencode_server. 2G/4G cgroup caps,
Restart=always (mitigates herdr#4920).
- modules/server/nginx.nix: herdr.zeroq.su vhost with Authelia
forward-auth (wildcard *.zeroq.su policy already covers it).
Upstream 127.0.0.1:7317 is the Bun server from the
devswha/herdr-web-ui plugin (970star, MIT) — vhost 502s until
'herdr plugin install devswha/herdr-web-ui' runs.
- modules/server/coredns.nix: 192.168.1.20 herdr.zeroq.su A record.
- home/server.nix: import the new module.
Три предыдущие попытки (a807701, e6e82b8, переход на unitConfig) закрепляли
баг вместо того, чтобы его лечить: они писали
systemd.services.gitea-runner-ci-sapphira (обычный дефис) при том, что
upstream регистрирует юнит как
nameValuePair "gitea-runner-${escapeSystemdPath name}"
а escapeSystemdPath превращает '-' в литеральный '\x2d'. Обе формы
рендерятся в один файл gitea-runner-ci-sapphira.service, но это два
разных атрибута; неэкранированный создавал фантомный юнит без
ExecStart, фантом выигрывал рендер, и systemd отказывался стартовать
("Service has no ExecStart=... Refusing."). Юнит молчал 12 часов
(2026-10-14 16:25 .. 2026-10-15 01:23), при этом сборка проходила.
Правка:
- unitKey = "gitea-runner-ci\\x2dsapphira" — байт-в-байт с upstream.
- systemd.services.${unitKey} = { ... } вместо двух разных attrset'ов.
- assertions-растяжка: падает на отсутствии ExecStart, чтобы будущий
rename upstream'а сломал сборку, а не юнит.
- wants/after = lib.mkAfter [ nginx.service gitea.service ... ] — как
first-class опции, не через unitConfig (те молча терялись).
- serviceConfig.RestartSec = lib.mkForce "30s" — upstream даёт 2s,
что крутит журнал при задержке TLS; Restart=on-failure уже был от
upstream, его не трогаем.
Хранилище: storage-guard через ConditionPathIsMountPoint убран. У живого
раннера ноль дескрипторов на /mnt/services (cwd /var/lib/gitea-runner/
ci-sapphira на rootfs, workdir-parent /tmp, токен /var/lib/gitea-runner/
registration-token на rootfs) — гвард охранял пустое множество. Вместо
этого Wants+After на nginx.service + gitea.service: реальная зависимость,
а не фикция.
Wants, не Requires: After= означает "started", а не "serving" — TLS
ещё не провижен в момент старта nginx (acme-git.zeroq.su.service
срабатывает позже). Requires отменил бы наш start-job при сбое gitea, и
отменённый job не триггерит Restart. Wants пробует рано, Restart=on-
failure + RestartSec=30s даёт retry-петлю.
См. ADR-0004 / R1.14, закрывает задачу T18.
Проверено на sapphira после nixos-rebuild switch 2026-10-15T01:23:
- systemctl is-active: active
- nix eval attrNames: только gitea-runner-ci\x2dsapphira, фантома нет
- rendered unit: ExecStart=…/gitea-runner daemon, Wants=network-online.
target nginx.service gitea.service, After=…+nginx.service gitea.service,
Restart=on-failure, RestartSec=30s, ConditionPathIsMountPoint отсутствует
The NixOS gitea-actions-runner module sets StateDirectory to private/gitea-runner
(mode 700 in /var/lib/), so symlink /var/lib/gitea-runner -> private/gitea-runner
resolves into a root-only directory tree. The static gitea-runner user (uid 973)
cannot traverse that tree → mkdir within host.workdir_parent failed with EACCES.
Move workdir_parent to /var/lib/gitea-runner-work (sibling of the symlink,
no parent traversal through /var/lib/private). tmpfiles creates it owned
by gitea-runner with mode 0755.
Also still using rootfs to avoid the bind-mount RO issue that bit earlier.
Workflow runs at 16:04 and 16:11 failed at:
mkdir /mnt/services/gitea-runner-work/<id>: read-only file system
The bind mount /mnt/services occasionally flips RO during nixos-rebuild
activation (transient window while systemd re-creates .mount units). It's
back to RW a few seconds later (verified manually at 19:11 as uid 973),
but act_runner fails fast — by the time the unit retries the mount is
still in its intermittent state, and the job's mkdir dies.
Move workspace to /var/lib/gitea-runner/work (rootfs, always RW). 4 GiB
eMMC has plenty of room for short-lived job scratch dirs.
Nixpkgs's services.gitea-actions-runner.module uses EnvironmentFile=
instance.tokenFile; systemd reads KEY=VALUE lines, not YAML. The previous
key="registration_token" with format="yaml" produced /var/lib/gitea-runner/
registration-token as YAML, which systemd silently failed to parse — the
runner process received an empty $TOKEN and Gitea replied with
"runner registration token not found".
Switch to format="dotenv" and drop the key= parameter (dotenv has no key
concept, the file is one TOKEN=... line). The companion secret file is
renamed accordingly:
secrets/gitea-runner-registration.yaml → secrets/gitea-runner-registration.env
Verified at 2026-10-14 17:36 MSK on sapphira with token in place — register
+ declare succeed, runner shows up green in Gitea admin UI.
ServiceConfig-level leaf assignments (or a single lib.mkMerge block) into
systemd.services.gitea-runner-ci-sapphira.serviceConfig were silently
replacing Nixpkgs's services.gitea-actions-runner module output: the
generated unit came out without ExecStart / ExecStartPre / LoadCredential
/ User / Restart / RestartSec / StateDirectory, so systemd refused to
start the service ('Service has no ExecStart=... Refusing').
[Unit]-side overrides DO merge, so the storage guard (ConditionPathIsMountPoint
on xlib.dirs.server-home) and the local-fs.target After= are kept.
Cgroup caps (CPUQuota, MemoryMax, OOM knobs) are deferred — a follow-up
should add them via a systemd drop-in
(/etc/systemd/system/gitea-runner-ci\x2dsapphira.service.d/override.conf)
so the upstream ExecStart path stays intact.
Verified at 2026-10-14 17:36 MSK: register + declare succeed on sapphira
after this commit's deploy + a sops format fix (next commit).
Replace the manual `ip tuntap add` + `ip link set master` pattern in the
VM service with the standard `-netdev bridge,helper=...` approach. This
removes the bespoke tap lifecycle from the systemd script and uses
qemu's own bridge helper for TAP creation/teardown.
What changed in vm.nix:
- Added security.wrappers.qemu-bridge-helper: a setuid root wrapper
at /run/wrappers/bin/qemu-bridge-helper that execs the nixpkgs
binary (${pkgs.qemu}/libexec/qemu-bridge-helper).
- Added /etc/qemu/bridge.conf restricting the helper to the pxe0
bridge (single `allow pxe0` line).
- Added /run/wrappers/bin to the service PATH and `helper=` option
on -netdev bridge, so qemu finds the wrapper.
- Removed the tap creation in the script and the teardown in
postStop — qemu-bridge-helper handles both.
- Inlined `chmod 4755` on the wrapper at the top of the service
script. The security.wrappers activation script in this NixOS
version (qemu 11.1.1, edk2 202608) doesn't always apply the
setuid bit, leaving the wrapper at mode 0511 which makes the
helper fail to create the TAP. The inlined chmod is idempotent
and runs as root (system service). Remove this once upstream
NixOS is fixed.
Verified 2026-10-14 on rydiwo:
- direct mode: VM boots, tap0 (created by helper) attaches to
pxe0, all network up.
- pxe mode: iPXE chain works end-to-end through the bridge —
snp.efi -> autoexec.ipxe -> boot.ipxe (vmlinuz-virt Not found is
expected; /latest/ copies were cleaned up after the H_fix.1b
test).
T10 fix (autoexec.ipxe on TFTP root) is independent and already
committed (7c9a8d8 + syntax fix ae14fec). Closes T13.
Nix indented strings use \x27\x27 (two single quotes) as delimiters, not \x27\x27\x27
(three). The autoexec.ipxe block added in 7c9a8d8 used \x27\x27\x27 which
the parser rejects with "unexpected end of file, expecting indented
string or \x27${ or end of an indented string". Replacing with the
correct \x27\x27 makes both copies (this one and the home-manager
symlink target) parse cleanly and unblocks nixos-rebuild.
iPXE in UEFI mode looks for autoexec.ipxe on the same TFTP server it
was loaded from, and runs it as the boot script. Without it, the iPXE
instance that replaced the firmware PXE ROM has nothing to chain to
and ends up in No more network devices -> #GP.
This was the root cause of T10 (the iPXE 2.0.0 #GP with RIP 0x7EE8A5FC
or 0x7EC9456F depending on which point in the chain it crashed at).
Adding a 1-line autoexec.ipxe that chains to the HTTP-served boot.ipxe
makes the full chain work end-to-end: snp.efi -> autoexec.ipxe ->
boot.ipxe -> vmlinuz-virt+initramfs-virt -> kernel boot -> Alpine Init.
ipxe.nix: new environment.etc entry autoexec.ipxe via pkgs.writeText.
default.nix: tmpfiles rule symlinks it into the served TFTP root.
Verified 2026-10-14 on rydiwo with manual QEMU test (H_fix.1b):
snp.efi (iPXE 2.0.0) loaded, autoexec.ipxe found, HTTP boot.ipxe
fetched, kernel+initrd downloaded, handoff to firmware, Alpine Init
ran. No #GP. Detailed diagnostic in pxe-infra-automation
.agent/notes/T10-diagnostic-2026-10-14.md.
The default "direct" preserves the proven E2E behavior
(2026-10-13). "pxe" enables the full L3 boot chain
(-boot n, no virtio drive) for reproducing T10 (iPXE 2.0.0
#GP at ExitBootServices, RIP 0x7EE8A5FC) and verifying any
fix. Switch modes by editing pxe-infra.vm.bootMode in
configurations/rydiwo and running nixos-rebuild switch —
no other changes needed.
iPXE 2.0.0 reliably #GPs at RIP 0x7EE8A5FC (RAX=0xAF...AF) when handing off a 1-2 GB raw image back to the firmware under QEMU/OVMF, regardless of whether the boot primitive is sanboot, imgfetch+boot, or kernel+initrd+boot, regardless of iPXE binary (universal or snp-only), and regardless of VM memory (2G or 4G). The image itself is fine (kernel+initrd extract cleanly, BOOTX64.EFI is in the ESP, systemd-boot config is set up). The crash is in iPXE 2.0.0 `s exit-to-firmware path under this QEMU/OVMF combination.
Workaround: attach the Alpine worker image as a local virtio drive in the QEMU command line. The firmware (OVMF) finds BOOTX64.EFI in the image's ESP and boots the kernel from the image's ext4 partition. The network is still there (pxe0-tap, dnsmasq, nginx, report-sink), so the runner inside the guest can still POST to the report-sink and the VM can still talk to the L2/L3 services at runtime. The image attached is the same artifact nginx serves for the real PXE rig (the `latest` symlink at `artifacts.root/http/latest/`); deploy.sh keeps both paths in sync.
Refs: docs/ARCHITECTURE.md section L4.
All four attempts to sanboot the Alpine raw image through iPXE crash at the same RIP offset (0x35FC from the iPXE image base) regardless of memory (2G or 4G), iPXE binary (universal or snp-only), or image virtual size (2G or 1G). Common factor: all used sanboot to present the URL as a block device.
Replace boot.ipxe with iPXE's kernel/initrd/boot primitive. This bypasses sanboot and the SAN device creation path entirely. The kernel will fail to find a rootfs (no /dev/sda* is exposed) and panic — but kernel boot messages in the journal will tell us whether iPXE's kernel-initrd handoff works at all. If it does, the bug is isolated to the sanboot/SAN-device code path. If it also crashes, the bug is in shared iPXE code (HTTP download buffer management, probably).
The previous run of imgfetch+boot crashed at RIP 0x7EE855FC in iPXE. iPXE was passing the full 2GB raw disk image to the firmware 'boot' primitive, which expects a UEFI PE executable (a small file with a PE header), not a 2GB block-device image. The firmware's PE loader hits uninitialised memory and the RIP-AF pattern reappears.
The earlier sanboot attempt also crashed, but that was before the systemd-boot fix gave the image a real \EFI\BOOT\BOOTX64.EFI. sanboot presents the URL as a block device, the firmware walks the GPT and finds the ESP, systemd-boot runs, and the kernel boots from the local ext4 partition. This is the right primitive for raw disk images served over HTTP.
Refs: docs/ARCHITECTURE.md section L4.
iPXE sanbooted the Alpine raw image and crashed with a #GP at RIP 0x7EE855FC, RAX=0xAF...AF — the AF pattern is the uninit-memory marker iPXE puts in block-device descriptors, which sanboot reads back. Splitting OVMF CODE+VARS did not change the RIP, which is in iPXE not OVMF, confirming the fault is on the iPXE side.
sanboot uses the legacy INT13 interface to present the URL as a disk; for a UEFI-only guest (B.6) the EFI firmware protocols are more direct. imgfetch downloads the (sparse, 159M actual) image into a memory block and boot invokes the EFI LoadImage/StartImage path on it, which is the same path the firmware would use for a normal disk boot. Removes the INT13 detour that was crashing.
Refs: docs/ARCHITECTURE.md section L4.
iPXE loaded boot.ipxe and tried to sanboot the Alpine raw image, but the firmware raised a #GP fault at RIP 0x7EC8B5FC with RAX=0xAF...AF. The AF pattern in RAX is a tell: it is the poisoned-memory value QEMU leaves in regions the firmware has not initialised. The combined OVMF.fd is read-only and carries no NVRAM region the firmware can write to, so ExitBootServices during the iPXE-to-image handoff cannot record its boot variables and the firmware crashes.
Switch to the split CODE+VARS form that nixpkgs ships: mount OVMF_CODE.fd read-only, seed a writable copy of OVMF_VARS.fd at /var/lib/pxe-infra/ovmf-vars.bin on first run, and pass it as a second pflash drive. iPXE can then write the chain target into NVRAM and the firmware hands off cleanly.
Refs: docs/ARCHITECTURE.md section L4.