Compare commits

...
15 changed files with 1375 additions and 83 deletions
+120
View File
@@ -0,0 +1,120 @@
# CMS Git CI: operating contract and next-repository onboarding
Ops source of truth: https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-78. Canon: DCPLATFORM-21; shared CI: DCPLATFORM-37.
## Начать здесь: назначение и источники
Рабочий маршрут подключения следующего приложения к Git CI на Synology, основанный на принятом DC CMS и опыте Device Core. Нормативный канон — https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-21 и его DEPLOY CANON ANCHOR 17.07.2026 (comment f99b03bd-5d6d-419f-b4ab-3e4601cfd0bf). Общая CI-архитектура и первый эталон Device Core — https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-37. Продукт CMS — https://ops.nodedc.ru/nodedc/browse/DC-9; сайт — DC-6; Device Core — DCPLATFORM-76.
Эта карта описывает текущий контракт, порядок действий и установленные причины отказов. Она не разрешает повторять исторические bootstrap/reconciliation-пакеты или переносить их exact predecessor на другой продукт. Перед новым проектом заполнить отдельный паспорт и сравнить его с двумя эталонами. Отличия сначала проектируются и проверяются; существующие guards не ослабляются.
## Подтверждённое состояние CMS
SILVER/DC_CMS, repositoryId=33, master, production https://cms.dcserve.ru/. Принятый source 5ea737318bc49d23cf90121224e5e4296ab579a5, Gitea run55, canonical release r55. Предыдущие обычные r52/r54 и r55 доставлены автоматически без NAS-команд оператора. Точный коммит master подтверждён повторным Git read.
Pipeline: push master → qualification точного SHA → Gitea artifact → исходящий контроллер с отдельной постоянной очередью → canonical plan/apply → cms-app → отдельная UI/API-приёмка. Это обновление приложения CMS. Сохранение контента сайта → render → SFTP на McHost — другой механизм, с собственной очередью и ограничениями. Site Registry, workspace, uploads и секреты сайтов не входят в application artifact.
Bootstrap dc-cms-autodeploy-v1-20261104-002 принят; повторная регистрация не требуется. Source инфраструктуры: NODEDC_PLATFORM 896b90e888ac2e6a77f64fca0e8fd1c3b6d747f5, ветка fix/device-r46-dns-reconciliation; CMS-ядро политики введено 6cf7a911471af5446f96879cb3616adc0aea21ca. Последняя подтверждённая оператором установка root runner: SHA256 52831367c42f991367f40170b5d9400e7fca34d906d15b19b1c549ef91846e88, Python3.8.15. Это зафиксированное доказательство установки, не гарантия неизменности сервера в будущем.
## Паспорт CMS: точные привязки
Source: https://git.dcserve.ru/SILVER/DC_CMS.git; master; event=push; workflow=ci.yml@refs/heads/master; один job qualify; label=nodedc-node22-build. Ровно два шага: Check the exact pushed commit; Retain the qualified release in this Gitea run. workflow_dispatch может квалифицировать, но текущий admission принимает только push.
Build runner: synology-cms-build, repo-scoped, observed ID=2. ID читается из проверенной root-private регистрации data/.runner и сопоставляется с run/job/name/repo/labels; 2 не является универсальной константой. Device Core имеет другую регистрацию (repo38/main, observed ID=1).
Runtime: /volume1/docker/dc-cms/source; фиксированные Compose/env/project dc-cms; service=cms-app. Bootstrap root /volume1/docker/nodedc-cms-autodeploy; private queue /var/lib/nodedc-cms-autodeploy. Units nodedc-cms-autodeploy.service и .timer в /usr/local/lib/systemd/system; root oneshot, OnBootSec=120s, OnUnitInactiveSec=30s; опубликованных портов нет. Приложение и его jobs не получают deploy authority.
Artifact: component=dc-cms-release; id=dc-cms-release-v1-r<runId>-<40-char-SHA>; descriptor server/cms-release.json; wrapper receipt release.json. runId, runNumber, attempt и source SHA — разные поля, их нельзя подменять друг другом.
## Три уровня доверия и секреты
CI job проверяет код и создаёт данные. У job нет production-реквизитов, произвольных volume mounts, privileged режима или Docker socket. Build-runner daemon имеет свой отдельно зарегистрированный доступ к Docker для запуска изолированных job-контейнеров; read-only bind socket сам по себе не делает Docker API безопасным, поэтому граница обеспечивается доверенным daemon и запретом передачи socket в jobs.
Admission controller только через закреплённый HTTPS origin/repo читает runs/artifacts. CMS использует существующую root-private read identity Device Core без копирования; доступ к repo33 проверен. Это выбор текущего внедрения, а не требование делить токен между будущими продуктами. Enrollment token, read token и секреты приложения имеют разные назначения. Enrollment передаётся отдельным приватным handoff, импортируется root-owned и удаляется из staging, не входит в TGZ/Git/логи/карточку.
Production исполняет только /usr/local/sbin/nodedc-deploy. Исходники контроллера/очереди детерминированно встроены в reviewed runner; runtime не импортирует Python с SMB. Private paths проверяются на owner/mode/type/symlink. Нельзя печатать Authorization, signed URL, raw inspect/Env, содержимое .runner и секретных JSON. В доказательствах допустимы хэши, имена полей и очищенные статусы.
## До разработки: снять факты и заполнить паспорт нового продукта
1. Прочитать DCPLATFORM-21, DCPLATFORM-37 и эту карту. Сверить код эталона с текущей веткой и deployed bytes. Снять исходный application/foundation/runtime baseline, accepted ledger и backup, health/auth и список сохраняемых данных/сервисов. Не включать CI поверх неизвестного predecessor.
2. Записать repo URL/numeric ID, production branch/event/workflow/job/steps, владельца, правило production intent, dependency commits, runtime/toolchain, точные build/Compose roots/env/project/services, health, rollback, queue namespace и activation floor. Все различия с CMS/Device Core выписать до реализации.
3. Проверить global и repository Actions, daemon RPC и регистрацию. REST endpoint регистрации не доказывает включённые Actions. На существующей Synology не переустанавливать Gitea и не повторять принятую регистрацию.
4. Проверить реальные kernel/Docker/cgroups capabilities, образы и resource budget. Принятый хост: Docker24.0.2, cgroupv1, CPUSet/CPUShares/memory/swap доступны, CFS quota/period и PIDs limit отсутствуют. CMS daemon: CPU7/shares64/512MiB; job: CPU7/shares128/2GiB, capacity1. Это проверенный профиль этого хоста, не значения для слепого копирования.
5. Сверить NAS POSIX inventory, включая невидимые по SMB @eaDir; base image RootFS и inherited config; поведение реального Compose, а не только direct docker build. Проверить runtime Node24 отдельно от CI Node22. Не считать healthy HTTP доказательством полного соответствия runtime.
## Квалификация точного коммита и воспроизводимость
Workflow создаёт пустой временный checkout и забирает точный gitea.sha. infra/ci/release.py требует HEAD=SHA и чистые tracked files; frozen npm ci --ignore-scripts для runtime и ui; node ui/build.mjs --check; синтаксис всех JS/MJS; multisite/publication/backup tests и Python release-contract tests. Сборка UI должна совпадать с committed admin assets. @nodedc-пакеты закреплены source SHA и archive hashes; компоненты не копируются в consumer как fork.
Артефакт содержит только allowlisted flat admin/server файлы и два точных package-файла, descriptor с hashes и foundationSha256. TGZ детерминирован: manifest.env + files.txt + payload; стабильный порядок, gzip mtime0. Снаружи Gitea ZIP содержит ровно TGZ + release.json. qualification/deployed=false означает только подготовку, не публикацию.
Не включать .env, credentials, runtime/site workspaces, медиа сайтов, ZIP-бэкапы, БД, node_modules, .git, symlinks/hardlinks, hooks или команды. Перед первым выпуском проверить tar/ZIP members, повторяемость SHA, denylist и полный путь скачивания через настоящий Gitea API. Зависимости из других реп должны быть опубликованы до квалификации.
## Admission: почему зелёного CI недостаточно
Проверяются фиксированные API origin/repo identity, pagination/discovery consistency, runId/runNumber/attempt/SHA/event/branch/workflow, единственный ожидаемый job и оба успешных шага, фактическая runner identity и labels. Неподходящие/красные/pending runs не получают deploy authority.
Artifact должен принадлежать этому repo/run/SHA, быть не истёкшим и иметь допустимый размер/receipt/digest. Допускается только точный same-origin signed artifact route; постоянный Authorization не передаётся в signed redirect. ZIP и внутренний TGZ проходят независимые проверки путей, типов, размеров и authority.
По parent graph доказывается installed → candidate → current master. Force push и расходящаяся история отклоняются. После скачивания и длительного plan run/source/ancestry проверяются повторно перед reservation/apply. Branch protection — отдельная политика репозитория; ancestry check не доказывает, что protection настроен. Изменение workflow/job/steps/runner является изменением доверенного контракта, а не косметической YAML-правкой.
## Постоянная очередь и восстановление после перезапуска
Отдельная SQLite WAL/synchronous FULL queue CMS хранит immutable repo/floor policy, run identity и deployment phase. Более ранний незавершённый run не обгоняется; duplicate не запускается повторно. Controller после crash сначала сверяет canonical applied/failed receipts и только потом принимает следующий release. Неоднозначный исход и failed rollback блокируют дальнейшее применение.
Очереди CMS и Device Core раздельны, production mutation сериализует общий canonical deploy lock. Timer исходящий, новых ingress/webhook endpoints нет. Исправление очереди не делается ручным SQL/reset: recovery допускается только зарегистрированным точным переходом после доказанного receipt. Не менять activation floor после включения для пропуска неудобной истории.
FirstRunNumber=1 и baseline 4c6f133 относятся только к исходной установке CMS. Для нового проекта floor вычисляется из его принятого baseline и фактической run history. На текущем сервере bootstrap002 terminal; повтор запрещён.
## Детерминированная база Docker до первого application apply
Mutable FROM node:24-alpine привёл к inherited Env drift при неизменных Dockerfile/Compose. Теперь resolver доказывает точный accepted image ancestor: полный strict RootFS prefix, platform и inherited Env/config; scoped Parent-chain с ограниченным Node-only cache fallback, без общего Docker inventory.
Если cache не содержит доказанную базу, допускается только source-registered Node24.18.0-alpine linux/amd64: manifest SHA256 4ba75f835bb8802193e4c114572113d4b26f95f6f094f4b5229d2a77773e0afc, config SHA256 91d56b2d4e1cf23103d90b0b024c1f489c288f9c3aba1042dd7279503b367de6. Plan читает/проверяет, но не pull. Только apply после exact proof может восстановить этот pinned digest при точном missing-image ответе. Permission/daemon/registry error не разрешает другой образ. Classic image ID=config digest и containerd ID=manifest digest проверяются относительно одной зарегистрированной пары.
Clean build имеет пустой projects, source Dockerfile не меняется. Во временном контексте FROM заменяется только на доказанный local image ID; DOCKER_BUILDKIT=0, --pull=false. Реальный BuildKit трактовал FROM sha256:<imageID> как repository и пытался сеть; legacy builder использует localID. После build до recreation сравниваются полный Env/Labels/config.
Compose добавляет ровно разрешённые project/service/version labels; builder воспроизводит принятые значения, а не текущую версию локального Compose. Другие/частичные/wrong labels отклоняются. Формат WorkingDir=/ и пустые User/Variant OCI/API обработаны только в проверенных границах. Рецепт CMS переносится на другой runtime только через его собственный registered base contract.
## Область application release и приёмка
dc-cms-release меняет только зарегистрированный source /volume1/docker/dc-cms/source и пересоздаёт cms-app с фиксированными Compose/env/project и --no-deps/--pull never. Runtime dependencies/Dockerfile/Compose не разрешено произвольно менять обычным release; initial foundation закрепляет adm-zip0.6.1. UI build dependencies отделены от runtime foundation.
Acceptance внутри apply проверяет auth health, exact application bytes в running image, новую generation/image, inherited configuration, env/mounts/network/ports, неизменность других Compose services, site/project content/config/secrets и сохранность runtime/данных. Rollback возвращает точные source и прежний image без rebuild. БД/тома не выбираются только потому, что приложение ими пользуется.
Initial install, installed update, rollback и migration — разные state-aware transitions. Новая dependency/schema/topology требует отдельного additive contract и tests. Manifest не выбирает roots/build commands/services/health/Compose/секреты; files.txt выбирает действие только внутри зарегистрированной политики.
## Порядок первого подключения нового репозитория
1. Завершить паспорт и read-only baseline. Если существующая инфраструктура уже подходит, переиспользовать её; не откатывать runner/Gitea к версиям из старых инструкций.
2. Добавить qualification и deterministic artifact builder; доказать clean Linux checkout, реальные downloads, negative payload/source tests.
3. Добавить отдельный recurring release domain и собственные allowlists, foundation, build/health/rollback. Проверить соседние компоненты и Python3.8 совместимость standalone runner. Incident recovery не копировать вместо normal update.
4. Разработать repo-specific admission и независимую queue/scheduler policy, registration/read credential import и activation floor. CMS показывает вариант отдельного bootstrap build-runner+timer; он может сначала ждать accepted baseline, но application mutation не начинается до полной регистрации и source proof.
5. Если нужен новый runner: отдельная reviewed SHA-pinned promotion, свежий verify-install, затем новый plan. Promotion ждёт свободное окно и повторно проверяет процессы после атомарного lock; чужой lock не удаляется. Пользователь не выполняет диагностические Docker/Python heredoc-команды.
6. Только data artifact скопировать в SMB inbox, сверить SHA, проверить lifecycle. Fresh plan → review точных scope/predecessor/SHA → один apply. Для автоконтроллера эти зарегистрированные проверки выполняются им штатно; routine push не требует ручного plan/apply.
7. Подтвердить installed baseline по ledger/archive/backup и отдельному UI/API сценарию. Проверить два последовательных реальных push, порядок, сохранность соседей, duplicate/outage/restart/failed-rollback tests. Не завершать на зелёном workflow.
8. Заполнить новую Ops-карту текущими версиями, точными доказательствами, ограничениями и ежедневным маршрутом; добавить только новые общие правила в DCPLATFORM-37.
## Ежедневный маршрут и ручные границы
Обычная работа: изменения кода → локальные необходимые проверки → commit → push production branch → qualification → canonical receipt → UI/API проверка. Для CMS branch=master. Увидеть success Actions и убедиться в успешном application receipt — два отдельных шага. Изменения контента через CMS не коммитятся обратно в Git автоматически.
При отдельном административном изменении runner допустим reviewed promotion и затем sudo /usr/local/sbin/nodedc-deploy verify-install. Для application artifact пользовательские NAS-команды только sudo /usr/local/sbin/nodedc-deploy plan <полный .tgz> и, после review, apply того же точного файла. Старый plan недействителен после runner/artifact/live-state изменения.
После deploy-ok runner сам завершил acceptance, архивирование и ledger. Inbox закономерно пуст. Не restage/reapply, не просить ручные post-apply Docker/health команды. Агент читает canonical lifecycle и выполняет отдельно продуктовую приёмку. No apply-latest, live-edit, SMB executable, compose down -v, volume prune, broad restart или прямой Docker API для обхода канона.
## Карта ошибок: симптом → доказательство → действие
«Installed application differs»: сначала exact files и NAS POSIX inventory. В bootstrap001 только flat @eaDir stream существующего allowlisted файла оказался невидим SMB; 10 app/foundation SHA совпали. Bootstrap002 отделил regular metadata, сохранив bytes; symlink/orphan/unknown paths остаются ошибкой. Не игнорировать все @eaDir/скрытые файлы.
«Qualification job mismatch»: сверить фактическую private registration. CMS получила ID2, скопированная Device policy ждала ID1. Правило исправлено на проверенную зарегистрированную identity; bootstrap/registration/queue не пересоздавались.
Runtime drift / failed rollback: наличие исходников и HTTP200 не доказывает rollback. CMS r39 — exact legacy SHA восстановлен только перестановкой двух Binds и пустыми DNS null/[] на трёх стабильных samples (16 кандидатов); Device r46 — только пустые DNS. Отдельные marker-only reconciliation приняты, затем новые releases. CMS fingerprintv2 сортирует только уникальные валидные bind-строки и нормализует пустые DNS; Device v3 добавляет пустые DNS к прежнему v2. Непустые значения и остальные поля не нормализуются.
Env drift нового image: сравнить inherited base/config до recreation. r40 штатно откатился; mutable Node tag заменён exact ancestry/config proof. Нельзя разрешать Env drift ради успешной сборки.
«Local base inventory invalid/outside bounds»: старый guard объединял разные причины; конкретный подслучай не доказан. Перейти на scoped ancestry/Node lookup с ограничениями и очищенными кодами, не увеличивать общий лимит вслепую.
«cms-base-missing»: проверить категории отдельно. Реальный Compose-label дефект воспроизведён и исправлен; затем NAS отклонил все пять кандидатов по layers. Один баг не доказывает единственную причину. Только registered immutable base с полным proof закрыл mismatch.
Node24 ERR_FS_CP_EEXIST при создании сайта: root уже зарезервирован; копирование детей в собственный root сохраняет no-overwrite/cleanup/symlink guards. Node22 CI сам по себе это не воспроизводил; нужен тест точной runtime-версии.
Promotion «Canonical runner is active»: ждать свободное окно и повторно проверять lock/processes, не убивать runner и не удалять чужой lock. Пустой/NUL-хвост SMB сразу после receipt: свежий bounded read/F_NOCACHE + lifecycle; не править журнал.
Доступ после смены Wi-Fi/VPN: отдельно DNS/route/current IFA/HTTPS/auth. Проблема доступа Mac не равна отказу NAS scheduler. Узкий route repair только в разрешённом контуре, без отключения TLS/VPN или смены токенов.
## Если выпуск не принят: обязательный порядок диагностики
Сначала записать exact commit/artifact SHA, установленный runner SHA, component/state transition, expected/actual field hashes, journal, backup, image/generation и rollback result. Raw Env и credentials не выводятся. Разделить qualification failure, preflight без mutation, healthy rollback, uncertain rollback и networking.
Если artifact ещё staged без terminal receipt, устранение причины и fresh plan может продолжить тот же кандидат, как r41. Если есть terminal failed/apply receipt, идентичный artifact не повторяется. После source correction — новый commit/run/patch/digest. При failed rollback или reconciliation-required — STOP mutation, read-only аудит; восстановление только новым точным registered transition после proof. Не reset queue и не переименовывать архив для обхода history.
Диагностика должна воспроизвести именно реальный путь (Compose vs direct build, Node24 vs Node22, NAS vs Docker Desktop). Unit success не доказывает live acceptance. Если причина неизвестна, она остаётся неизвестной: r9 Device runtime field и Gitea FinalizeArtifact r15 не объясняются последующими успешными runs.
## Принятые доказательства и регрессионные условия
CMS r55: source 5ea737318bc49d23cf90121224e5e4296ab579a5 → infra/ci/release.py → https://git.dcserve.ru/SILVER/DC_CMS/actions/runs/55 → nodedc-dc-cms-release-v1-r55-5ea737318bc49d23cf90121224e5e4296ab579a5.tgz, SHA256 c099a5dbd8c4d23b3ea4dd141948428277a2f06c11d66c274ff9f1b643db096d → applied 2026-11-05T19:45:01Z → backup dc-cms-release-dc-cms-release-v1-r55-5ea737318bc49d23cf90121224e5e4296ab579a5-20261105-224253. terminal_success, 10/10 runtime files exact. 25 Node +3 Python tests; UI build deterministic. Production: Authentik вход, два независимых сайта, Save→SFTP текста/SEO/knowledge/изображения, скачивание двух ZIP и CRC. Restore проверен в изолированном workspace; production restore не проводился.
Device r48: source fc2e9c8bc165f5f304690ecbf96efe33cbff2543 → run48 → nodedc-device-core-release-v1-r48-fc2e9c8bc165f5f304690ecbf96efe33cbff2543.tgz, SHA256 b43933fdd8c08185ef15d96023a6de2120b7b8c6df3e5327ccafc722d8c20898; applied 2026-11-05T11:36:53Z; 78/78 files exact, preserved Postgres/gateway/backhaul. Product header/settings checked. Exact backups в DCPLATFORM-76.
CMS r39 recovery: nodedc-dc-cms-r39-runtime-reconciliation-v2-20261104-001.tgz, SHA28fe141601d412e470aa8f6284dc93dee22c3d3dd60cafc4f7bcd7ef1c62a651, applied2026-11-04T20:28:35Z. Device r46 recovery: nodedc-device-core-release-r46-reconciliation-v1-20261105-001.tgz, SHA3ea603aad4bca9b313ee30dc8160a2168ddaca8df479194c35533687c6dd1a7d, applied2026-11-05T11:31:55Z. Оба services/build/runtime-mutation=none; original failed evidence сохранено. Не являются пакетами для повторного применения.
Методные доказательства и ограничения: R39_RUNTIME_RECONCILIATION.md, R40_BUILD_BASE.md, R41_BASE_DISCOVERY.md, R41_COMPOSE_LABELS.md, R41_NODE_BASE_ACQUISITION.md, R46_DNS_RECONCILIATION.md в pinned Platform source. Реальная local Compose/BuildKit integration проверяла config/labels/layers, но NAS совпадение базы доказано отдельно только успешным canonical r41 apply.
## Открытые границы, которые нельзя выдавать за готовность
Нет универсального self-service подключения любой репы: CMS и Device Core имеют отдельные policies/controllers/queues. Dockerfile/dependency/Compose/schema migrations не входят автоматически в ordinary release. Общая throughput/capacity при росте количества реп, retention/GC, credential rotation, pause/resume и disaster recovery требуют своих проверок.
Gitea artifact retention30дней; controller имеет bounded pagination/ancestry/download. Очередь не гарантирует доставку уже удалённого artifact. Source-overlay строится на NAS; это не image-release из Container Registry. Не утверждать отсутствие риска или гарантированную первую попытку: паспорт и предварительные тесты устраняют уже известные классы ошибок, новые различия требуют proof.
Отдельная SFTP-очередь сайтов пока in-process, без durable restart recovery, remote prune, atomic swap и remote rollback; эта граница не относится к durable Git-release queue CMS. Site-scoped RBAC/generic adapter/CMS→Git autosync не реализованы.
## Исходники, запуск проверок и правило актуализации
CMS: .gitea/workflows/ci.yml; infra/ci/release.py и test_release.py; ui/design-system.lock.json; docs/multisite.md. Platform: infra/cms-deploy/{README.md,CI_RUNBOOK.md,autodeploy-v1.json,autodeploy_runtime.py,controller.py,deployment_queue.py,gitea_source.py,release_runtime.py,embed_runtime.py,build_autodeploy.py,test_*.py}; infra/device-core-deploy/{controller.py,deployment_queue.py,R46_DNS_RECONCILIATION.md}; infra/deploy-runner standalone runner.
Локальная проверка изменений политики: python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'; регрессии Device Core deploy; Python3.8 grammar; deterministic embed/build; negative authority/denylists/rollback; затем реальные Compose/runtime probes только в разрешённой изоляции. Команды app qualification задаёт infra/ci/release.py. Повторять production bootstrap ради проверки запрещено.
После изменения обновлять текущие версии/контракт/ограничения и результат проверки. Не добавлять хронологический дневник каждой попытки. Значимые эксперименты сводить к условию → наблюдению → выводу/ограничению → evidence. Новые общие правила переносить также в DCPLATFORM-37, канонические authority изменения — DCPLATFORM-21. Локальные сырые traces и копии карточек находятся в outputs/review/closure и профильных review-каталогах этого чата; в Ops не помещать секреты.
+79 -63
View File
@@ -1,77 +1,93 @@
# CMS Git deployment domain # CMS Git deployment domain
Source: SILVER/DC_CMS, repository 33, master. Push → qualification → Gitea artifact → outbound durable queue → canonical installer. The accepted CMS pipeline is live: `SILVER/DC_CMS`, repository 33, `master` → exact
qualification → Gitea artifact → outbound durable queue → canonical installer.
The accepted application release is r55, source
`5ea737318bc49d23cf90121224e5e4296ab579a5`. Bootstrap 002 and the incident-specific
reconciliation transitions are terminal; do not replay them.
The Device Core runner is scoped only to its own repository. CMS therefore registers its own build-runner in project nodedc-cms-ci, with the accepted Synology v4 resource and isolation profile. Existing Device Core registration, source and units are untouched. Both pinned images must already exist; bootstrap pulls neither. New runner registration is repository-scoped, staged separately from artifacts, imported to root0600 and removed from handoff storage. No credentials appear in Git, receipts or workflow artifacts. Read [CI_RUNBOOK.md](CI_RUNBOOK.md) before modifying this domain or onboarding
another repository. The living operational card is
[DCPLATFORM-78 — CMS Git CI](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-78).
[DCPLATFORM-21](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-21) remains the
mandatory deployment canon; [DCPLATFORM-37](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-37)
is the shared CI and Device Core reference.
`dc-cms-autodeploy` bootstraps exactly three source files under /volume1/docker/nodedc-cms-autodeploy, one build-runner service and two systemd units. Root-private queue state is /var/lib/nodedc-cms-autodeploy. Its read-only Gitea client uses the existing private Device Core read identity without copying it; preflight checks actual access to repository 33. The installed canonical receipt gates polling. Bootstrap preserves all preexisting containers and CMS data; rollback removes only the new runner/units/source partition, retaining private enrollment and queue for diagnosis. ## Authority and isolation
`dc-cms-release` allows only flat admin/server application files and two exact dependency files. The initial predecessor is original CMS commit 4c6f133 with SMB-verified hashes in baseline.json. Foundation pins adm-zip 0.6.1 in foundation.json to fix known ZIP vulnerabilities. No later dependency, Dockerfile, Compose or Caddy change is admitted by this domain. Build uses the registered Dockerfile in an isolated temporary context with an empty projects directory. Only the temporary FROM line is replaced by the exact cached Node image ID proved against the accepted application's layer ancestry and inherited configuration; see [the build-base contract](R40_BUILD_BASE.md). The canonical installer restarts only cms-app with no dependencies, no image pull and no rebuild during rollback. Acceptance verifies authentication, app hashes inside the running container, image generation, fixed ZIP dependency version, preserved env/mounts/networks/ports, other Compose services and site/project data. CMS has its own repository-scoped `synology-cms-build` registration, controller,
SQLite queue and systemd service/timer. Registration identity is read from the
verified root-private record; it is not copied from Device Core. Its read client
uses the existing private read identity with access to repository 33. Enrollment,
application secrets and site workspaces never enter Git or release artifacts.
The daemon has the reviewed Synology CPUSet/memory isolation profile; job containers
have no Docker socket, production credentials or arbitrary host volumes.
## Build and checks Only the installed root-owned `/usr/local/sbin/nodedc-deploy` executes production
transitions. Source/controller modules are embedded deterministically, never
imported from writable SMB at runtime. A new application cannot choose roots,
services, Compose context, build commands or acceptance through its manifest.
`python3 infra/cms-deploy/embed_runtime.py` refreshes only the explicitly marked standalone section. Registry and dispatcher wiring are ordinary reviewed runner source. Runtime never imports the fragment files from SMB. ## Application release contract
`python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'` `dc-cms-release` accepts only registered flat `admin`/`server` application files,
`python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'` the exact two dependency files and `server/cms-release.json`. Runtime dependencies,
`python3 infra/cms-deploy/build_autodeploy.py --output-dir <directory>` Dockerfile and Compose changes require a separate reviewed foundation transition.
The initial foundation pins `adm-zip` 0.6.1. UI build dependencies are separate;
qualification verifies the committed UI assets against the frozen package build.
Before production: SHA-pinned root runner promotion and verify-install; then fresh canonical plan/apply of the bootstrap artifact. Ordinary CMS pushes afterward need no operator NAS commands. A queued or green Actions run alone is not deployment evidence; require canonical receipt and product acceptance. The clean temporary build context has an empty `projects` directory. The inherited
Node base must match accepted image ancestry and full configuration. A registered
immutable base can be restored only after exact proof; plan never pulls. Build
uses a proved local image ID and preserves Compose-owned labels. See
[R41_NODE_BASE_ACQUISITION.md](R41_NODE_BASE_ACQUISITION.md) for exact digests and limits.
The source Dockerfile is not rewritten. Application recreation selects only
`cms-app`, with fixed Compose/env/project, `--no-deps` and no implicit pull.
Rollback restores the prior image without rebuilding it.
Bootstrap 002 corrects the initial POSIX inventory: the NAS contains a Synology Acceptance checks authentication/health, exact running application bytes,
`server/@eaDir/admin-server.mjs@SynoEAStream` file hidden from SMB. The original image/generation, env/mounts/network/ports, other services and site/project data.
application and foundation hashes were confirmed unchanged through both paths. CMS fingerprint v2 normalizes only validated bind ordering and explicitly empty
Only flat `admin|server/@eaDir/<present-application-file>@SynoEAStream` regular DNS representations. Synology metadata is classified narrowly and preserved;
files are classified as metadata. Orphaned streams, unknown paths and symlinks unknown paths, orphan streams and symlinks are rejected.
remain errors. Metadata is excluded from application identity and clean image
build inputs, and preserved byte-for-byte across application release/rollback.
The same partition handles old images containing these non-code streams; all
application hashes are still exact. Bootstrap 001 failed during read-only plan,
never entered apply, and is superseded rather than retried or overwritten.
After bootstrap 002 was accepted, Gitea assigned CMS runner ID 2. The initial ## Qualification and verification
copied source verifier still required Device Core's ID 1 and rejected successful
run 39 before staging or deployment. Qualification now receives the ID from the
root-private CMS `data/.runner` registration; it verifies exact runner name,
repository, labels, job, steps, run identity and artifact ownership. Registration
IDs are allocated by Gitea, so no fixed numeric fallback is permitted. This
controller correction preserves the accepted bootstrap 002 receipt and private
queue; it does not rerun bootstrap or re-register/restart the build daemon.
Release r39 then reached canonical apply but failed runtime-config acceptance; CMS owns `.gitea/workflows/ci.yml` and `infra/ci/release.py`. Only successful exact
its automatic rollback restored the original source and healthy authenticated `push` runs on `master` are admitted; workflow dispatch is not a production trigger.
CMS, while full runtime equivalence remained unproven. The failed receipt and The controller checks repository/run/attempt/source/job/steps/registered runner,
controller reconciliation barrier stay intact. `dc-cms-runtime-audit` is a artifact ownership/digest and installed → candidate → current-branch ancestry.
separate **plan-only** diagnostic domain pinned to that exact incident, archive Its durable queue reconciles canonical receipts after interruption and blocks on
and six backup-file hashes. It reads current source/data/image/runtime evidence uncertain rollback. No manual NAS command is needed for an ordinary qualified push.
and reports a bounded saved-digest preimage search without accepting any drift.
No environment values or raw Docker inspection are printed. `apply` is forbidden;
no application, queue, receipt or service is changed by this audit. Recovery must
be a separately reviewed transition after its actual runtime findings.
After diagnostic runner promotion, build its fixed data bundle with For changes to deployment policy:
`python3 infra/cms-deploy/build_runtime_audit.py --output-dir <directory>` and
use only the canonical `plan` operation for the audit artifact.
The r39 audit confirmed the old image and all source/data/dependency checks. ```sh
Offline reconstruction matched the complete current fingerprint and the complete python3 infra/cms-deploy/embed_runtime.py
saved predecessor fingerprint: only bind-string order and three empty DNS list python3 -m unittest discover -s infra/cms-deploy -p 'test_*.py'
representations differ. See [the incident proof and recovery contract](R39_RUNTIME_RECONCILIATION.md). python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'
The separate `dc-cms-runtime-reconciliation` marker transition re-proves that ```
exact legacy hash on NAS before releasing the r39 barrier. It never retries r39.
Reconciliation was accepted at 2026-11-04T20:28:35Z. The next qualified run r40 Embedding is needed only after source changes to the embedded modules. Also check
failed only `config.Env`; its automatic rollback passed completely. r40 is also Python 3.8 grammar, deterministic artifact bytes, negative authority/rollback cases
terminal and must not be replayed. The new r41 commit qualified and staged, and the real Compose/runtime path. Documentation-only updates do not promote or
but the original global image lookup was rejected during preflight. The install a runner. Existing source commits, artifacts and acceptance evidence are
[scoped discovery correction](R41_BASE_DISCOVERY.md) follows CMS image ancestry, listed in the runbook; a green CI run alone is not production deployment evidence.
with a bounded Node-only cache fallback and safe public error codes. After
runner promotion the controller may resume staged r41 with a fresh plan; ## Failure contracts
no bootstrap or failed-release replay is needed.
The scoped runner was installed; its preflight reported no matching base. - [R39 runtime proof](R39_RUNTIME_RECONCILIATION.md): exact bind/DNS reconciliation,
The [Compose-label correction](R41_COMPOSE_LABELS.md) accounts for the three no runtime mutation, immutable failed receipt.
labels added by Compose, reproduces them during build, and retains exact - [R40 base drift](R40_BUILD_BASE.md): mutable tag changed inherited image state;
post-build configuration comparison. That runner was installed; all five local strict rollback remained intact.
Node candidates still failed the filesystem-prefix check. The - [R41 scoped discovery](R41_BASE_DISCOVERY.md): bounded ancestry/cache lookup,
[registered base-acquisition policy](R41_NODE_BASE_ACQUISITION.md) can restore no broad Docker inventory assumptions.
one pinned public Node base only after exact preflight ancestry/config proof. - [R41 Compose labels](R41_COMPOSE_LABELS.md): reproduced Compose additions are
Deployment is pending promotion of that policy and actual NAS acceptance. preserved; this alone did not prove a matching NAS filesystem base.
- [R41 registered acquisition](R41_NODE_BASE_ACQUISITION.md): one exact public base,
full ancestry/config proof, then successful application installation.
These documents preserve the conditions and limitations of the investigated cases.
Their intermediate pending states are not current operational status. Use the
runbook and fresh canonical receipts for current state. CMS content publication
and portable site backups are separate product flows documented in DC-9.
+18 -3
View File
@@ -66,15 +66,30 @@ class CmsRunnerTests(unittest.TestCase):
restore.assert_called_once();compose.assert_called_once();accept.assert_called_once_with(before,rollback=True) restore.assert_called_once();compose.assert_called_once();accept.assert_called_once_with(before,rollback=True)
self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','tag','old-id','dc-cms-cms-app']) self.assertEqual(run.call_args.args[0],[str(r.DOCKER),'image','tag','old-id','dc-cms-cms-app'])
def test_existing_device_domain_unchanged(self): def test_unrelated_domains_unchanged_except_reviewed_r46_extension(self):
old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True) old=subprocess.check_output(['git','show','27c155276a703dd4fd39385011fc5e3f86afcae4:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
current=RUNNER.read_text() current=RUNNER.read_text()
def domain(source):return source[source.index('# Device Core outbound automatic deployment.'):source.index('# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY')]
self.assertEqual(domain(old),domain(current))
allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'} allowed={'allowed_payload_path','load_artifact','component_services','plan_artifact','apply_artifact','run_healthchecks','main'}
# The separately reviewed r46 recovery now changes these Device entry
# points. Its exact identity, v1/v2 compatibility and queue transitions
# are tested in device-core-deploy/test_r46_reconciliation.py.
allowed.update({'device_release_predecessor','validate_device_release_reconciliation_payload',
'preflight_device_release_reconciliation','device_release_capture_field_digests',
'device_release_runtime_drift_message','preflight_device_release','accept_device_release',
'DeviceAutodeployInstaller','device_autodeploy_library'})
old_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(old).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))} old_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(old).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
current_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(current).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))} current_functions={n.name:ast.dump(n,include_attributes=False) for n in ast.parse(current).body if isinstance(n,(ast.FunctionDef,ast.ClassDef))}
for name,node in old_functions.items(): for name,node in old_functions.items():
if name not in allowed:self.assertEqual(current_functions[name],node,name) if name not in allowed:self.assertEqual(current_functions[name],node,name)
def methods(source):
cls=next(n for n in ast.parse(source).body if isinstance(n,ast.ClassDef) and n.name=='DeviceAutodeployInstaller')
return {n.name:ast.dump(n,include_attributes=False) for n in cls.body if isinstance(n,ast.FunctionDef)}
before,after=methods(old),methods(current)
for name,node in before.items():
if name!='receipt':self.assertEqual(after[name],node,name)
# None of the CMS runtime changes as part of Device recovery.
baseline=subprocess.check_output(['git','show','6cf7a91:infra/deploy-runner/nodedc-deploy'],cwd=ROOT,text=True)
def cms(source):return source.split('# BEGIN GENERATED CMS DEPLOYMENT\n',1)[1].split('# END GENERATED CMS DEPLOYMENT\n',1)[0]
self.assertEqual(cms(baseline),cms(current))
if __name__=='__main__':unittest.main() if __name__=='__main__':unittest.main()
+276 -12
View File
@@ -5053,7 +5053,7 @@ def allowed_payload_path(component, rel):
return True return True
die("Device Core drift audit accepts only its exact descriptor") die("Device Core drift audit accepts only its exact descriptor")
if component == "device-core-release-reconciliation": if component == "device-core-release-reconciliation":
if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ENTRY): if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY, DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, DEVICE_R46_RECON_ENTRY):
return True return True
die("Device Core reconciliation accepts only its exact descriptor") die("Device Core reconciliation accepts only its exact descriptor")
if component == "device-core-release": if component == "device-core-release":
@@ -22581,7 +22581,7 @@ def component_services(component, entries=None):
die("Device Core drift audit requires the exact descriptor entry") die("Device Core drift audit requires the exact descriptor entry")
return () return ()
if component == "device-core-release-reconciliation": if component == "device-core-release-reconciliation":
if tuple(entries or ()) not in ((DEVICE_RELEASE_RECONCILIATION_ENTRY,), (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,)): if tuple(entries or ()) not in ((DEVICE_RELEASE_RECONCILIATION_ENTRY,), (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,), (DEVICE_R46_RECON_ENTRY,)):
die("Device Core reconciliation requires the exact descriptor entry") die("Device Core reconciliation requires the exact descriptor entry")
return () return ()
if component == "device-core-release": if component == "device-core-release":
@@ -32715,7 +32715,7 @@ def device_release_predecessor(candidate):
applied = load_state(STATE_FILE) applied = load_state(STATE_FILE)
for row in load_state(FAILED_STATE_FILE): for row in load_state(FAILED_STATE_FILE):
if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"): if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"):
if not device_release_r5_reconciled(row): if not device_release_r5_reconciled(row) and not device_r46_reconciled(row):
die("Device Core release requires reconciliation of a failed rollback") die("Device Core release requires reconciliation of a failed rollback")
normal = [row for row in applied if row.get("component") == "device-core-release"] normal = [row for row in applied if row.get("component") == "device-core-release"]
installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY
@@ -32878,6 +32878,8 @@ def device_release_reconciliation_v2_descriptor():
def validate_device_release_reconciliation_payload(payload, entries, patch_id): def validate_device_release_reconciliation_payload(payload, entries, patch_id):
if tuple(entries) == (DEVICE_R46_RECON_ENTRY,):
return validate_device_r46_payload(payload, entries, patch_id)
if tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,): if tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,):
if (patch_id != DEVICE_RELEASE_RECONCILIATION_V2_ID or if (patch_id != DEVICE_RELEASE_RECONCILIATION_V2_ID or
read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, "Device Core reconciliation v2") != device_release_reconciliation_v2_descriptor()): read_strict_json(payload / DEVICE_RELEASE_RECONCILIATION_V2_ENTRY, "Device Core reconciliation v2") != device_release_reconciliation_v2_descriptor()):
@@ -32930,6 +32932,8 @@ def device_release_r5_evidence():
def preflight_device_release_reconciliation(payload, entries, patch_id, *, marker_installed=False): def preflight_device_release_reconciliation(payload, entries, patch_id, *, marker_installed=False):
if tuple(entries) == (DEVICE_R46_RECON_ENTRY,):
return preflight_device_r46_reconciliation(payload, entries, patch_id, marker_installed=marker_installed)
validate_device_release_reconciliation_payload(payload, entries, patch_id) validate_device_release_reconciliation_payload(payload, entries, patch_id)
v2 = tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) v2 = tuple(entries) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,)
marker = DEVICE_PLANE_ROOT / entries[0] marker = DEVICE_PLANE_ROOT / entries[0]
@@ -33181,7 +33185,7 @@ def device_release_field_digests(fields):
return result return result
def device_release_capture_field_digests(expected_runtime): def device_release_capture_field_digests(expected_runtime, version=2):
"""Bind diagnostics to the already checked container generation and digest.""" """Bind diagnostics to the already checked container generation and digest."""
observations = device_release_drift_sample() observations = device_release_drift_sample()
if set(observations) != set(expected_runtime): if set(observations) != set(expected_runtime):
@@ -33189,7 +33193,7 @@ def device_release_capture_field_digests(expected_runtime):
result = {} result = {}
for service, sample in observations.items(): for service, sample in observations.items():
expected = expected_runtime[service] expected = expected_runtime[service]
fields = device_release_mounts_v2(sample["fields"]) fields = (device_release_fields_v3 if version == 3 else device_release_mounts_v2)(sample["fields"])
if (sample["runtime"]["containerId"] != expected["containerId"] if (sample["runtime"]["containerId"] != expected["containerId"]
or sample["runtime"]["imageId"] != expected["imageId"] or sample["runtime"]["imageId"] != expected["imageId"]
or device_release_drift_digest(fields) != expected["runtimeConfigSha256"]): or device_release_drift_digest(fields) != expected["runtimeConfigSha256"]):
@@ -33213,7 +33217,7 @@ def device_release_runtime_drift_message(before, current, service):
or not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value) or not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value)
for key, value in expected.items()): for key, value in expected.items()):
die("Device Core saved runtime field digests are invalid") die("Device Core saved runtime field digests are invalid")
actual = device_release_capture_field_digests(current)[service] actual = device_release_capture_field_digests(current, before.get("runtimeFingerprintVersion", 1))[service]
changed = sorted(key for key in set(expected) | set(actual) if expected.get(key) != actual.get(key)) changed = sorted(key for key in set(expected) | set(actual) if expected.get(key) != actual.get(key))
report["changedFields"] = [{"path": key, "expectedSha256": expected.get(key), report["changedFields"] = [{"path": key, "expectedSha256": expected.get(key),
"actualSha256": actual.get(key)} for key in changed[:64]] "actualSha256": actual.get(key)} for key in changed[:64]]
@@ -33285,11 +33289,11 @@ def preflight_device_release(payload, entries, patch_id):
die("Device Core release changes the immutable database/build foundation") die("Device Core release changes the immutable database/build foundation")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True) validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True)
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES) run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
before = device_release_runtime_snapshot_v2() before = device_release_runtime_snapshot_v3()
field_digests = device_release_capture_field_digests(before) field_digests = device_release_capture_field_digests(before, 3)
validate_installed_device_b2() validate_installed_device_b2()
compose = {str(p): sha256_file(p) for p in component_compose_files("device-core-release")} compose = {str(p): sha256_file(p) for p in component_compose_files("device-core-release")}
return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", return {"runtimeFingerprintVersion": 3, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
"runtime": before, "runtimeFieldDigests": field_digests, "runtime": before, "runtimeFieldDigests": field_digests,
"compose": compose, "otherComposeServices": device_release_other_compose_services(), "compose": compose, "otherComposeServices": device_release_other_compose_services(),
"installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")} "installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")}
@@ -33297,9 +33301,9 @@ def preflight_device_release(payload, entries, patch_id):
def accept_device_release(before, *, rollback=False): def accept_device_release(before, *, rollback=False):
version = before.get("runtimeFingerprintVersion", 1) version = before.get("runtimeFingerprintVersion", 1)
if type(version) is not int or version not in (1, 2): if type(version) is not int or version not in (1, 2, 3):
die("Device Core release runtime fingerprint version mismatch") die("Device Core release runtime fingerprint version mismatch")
current = device_release_runtime_snapshot_v2() if version == 2 else device_release_runtime_snapshot() current = (device_release_runtime_snapshot_v3 if version == 3 else device_release_runtime_snapshot_v2 if version == 2 else device_release_runtime_snapshot)()
for service, old in before["runtime"].items(): for service, old in before["runtime"].items():
new = current[service] new = current[service]
if service not in DEVICE_RELEASE_SERVICES: if service not in DEVICE_RELEASE_SERVICES:
@@ -39646,7 +39650,8 @@ def run_healthchecks(component, entries=None, services=None):
if component == "device-core-release-reconciliation": if component == "device-core-release-reconciliation":
if tuple(services or ()) != (): if tuple(services or ()) != ():
die("Device Core reconciliation must not select services") die("Device Core reconciliation must not select services")
identity = DEVICE_RELEASE_RECONCILIATION_V2_ID if tuple(entries or ()) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) else DEVICE_RELEASE_RECONCILIATION_ID identity = (DEVICE_R46_RECON_ID if tuple(entries or ()) == (DEVICE_R46_RECON_ENTRY,) else
DEVICE_RELEASE_RECONCILIATION_V2_ID if tuple(entries or ()) == (DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,) else DEVICE_RELEASE_RECONCILIATION_ID)
preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, identity, marker_installed=True) preflight_device_release_reconciliation(DEVICE_PLANE_ROOT, entries, identity, marker_installed=True)
return return
if component == "device-core-release": if component == "device-core-release":
@@ -42390,6 +42395,8 @@ class DeviceAutodeployInstaller:
return 'ambiguous', 'canonical-archive-or-backup-mismatch' return 'ambiguous', 'canonical-archive-or-backup-mismatch'
if applied and record.get('status') == 'ok': if applied and record.get('status') == 'ok':
outcome = 'deployed' outcome = 'deployed'
elif failed and device_r46_reconciled(record):
return 'rolled-back', 'canonical-reconciled:' + DEVICE_R46_RECON_ID
elif failed and record.get('rollback_status') == 'ok:device-core-release': elif failed and record.get('rollback_status') == 'ok:device-core-release':
outcome = 'rolled-back' outcome = 'rolled-back'
else: else:
@@ -42634,6 +42641,30 @@ def device_autodeploy_library():
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply) self.transaction(apply)
def reconcile_r46(self, identity, *, digest, artifact, receipt):
"""Exact terminal blocked -> failed recovery after canonical proof.
This never makes the failed artifact ready again. The caller verifies
the immutable failed evidence and the separate successful recovery.
"""
sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab'
expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001'
if (type(identity) is not int or identity != 46
or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba'
or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz'
or receipt != expected_receipt):
raise QueueError('r46_reconciliation_identity_mismatch')
def apply():
row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone()
if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact):
raise QueueError('r46_reconciliation_row_mismatch')
if row['phase'] == 'failed' and row['receipt'] == receipt:
return
if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed':
raise QueueError('r46_reconciliation_predecessor_mismatch')
self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity))
self.transaction(apply)
def snapshot(self): def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
@@ -42907,6 +42938,13 @@ def device_autodeploy_library():
def reconcile(self): def reconcile(self):
for row in self.queue.snapshot(): for row in self.queue.snapshot():
if row['phase'] == 'blocked':
outcome, receipt = self.installer.receipt(row)
if outcome == 'rolled-back':
self.queue.reconcile_r46(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt)
elif outcome != 'ambiguous':
raise QueueError('blocked_run_requires_exact_recovery')
continue
if row['phase'] != 'deploying': if row['phase'] != 'deploying':
continue continue
outcome, receipt = self.installer.receipt(row) outcome, receipt = self.installer.receipt(row)
@@ -45031,6 +45069,232 @@ def cms_autodeploy_library():
return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError) return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)
# END GENERATED CMS DEPLOYMENT # END GENERATED CMS DEPLOYMENT
# BEGIN GENERATED DEVICE R46 RECOVERY
"""Versioned DNS representation fingerprint and exact r46 evidence-only recovery.
Embedded into the root-owned runner. No production code is imported from SMB.
Historical v1/v2 hashes are never reinterpreted without an exact preimage proof.
"""
DEVICE_R46_EVIDENCE = {'backupHashes': {'device-release-before.json': '52927379518030d1e979d897e5cb298481d81a78fb694c5ab68896bfeb8a64d4', 'existing-files.txt': '4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a', 'files.txt': '4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a', 'manifest.env': 'c126a1df2b28d0474e80727e5716311ea6b9aa5702f6b76e9d4742205d87ba62', 'missing-files.txt': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'source-before.tgz': 'dc40d86d52be8f7e02fb7ec0928da371e37f813676bba182fb883212cc7ec967'}, 'cms': [{'backupSha256': '1156f7bdc0313cb4ad8f2541cbe260e965784201b18baacb548480ee6add902d', 'row': {'applied_at': '2026-11-05T10:32:58+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1-20261105-133137', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1', 'sha256': 'dfd7bbc8753af8b6693253a5a7030995fc6745e541e5206ca1e708bf17555a5d', 'status': 'ok'}}, {'backupSha256': '6a800c80d6cd533bf7d31745baa20ab9912ac9c93f1e9febbe19a61006650547', 'row': {'applied_at': '2026-11-05T10:35:39+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835-20261105-133344', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835', 'sha256': 'd69852e99b251310bc96ec88dcc89d9d16ca704c49f35d8a168c2835440652b0', 'status': 'ok'}}, {'backupSha256': '2b96d060d5aee54998dabb1c432fe495469cebc92a59b859ff00a0c1183690ca', 'row': {'applied_at': '2026-11-05T10:54:15+00:00', 'artifact': 'nodedc-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3.tgz', 'backup_id': 'dc-cms-release-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3-20261105-135303', 'component': 'dc-cms-release', 'id': 'dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3', 'sha256': '88a09153b860280c0a28c51e13bbe8d68cb39e7030ce2ba70bc9a0bf8a367c43', 'status': 'ok'}}], 'failedRow': {'artifact': 'nodedc-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab.tgz.20261105-132438', 'backup_id': 'device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438', 'component': 'device-core-release', 'failed_at': '2026-11-05T10:30:32+00:00', 'id': 'device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab', 'message': 'Device Core release runtime configuration drift: device-control-core; field_evidence={"actualSha256":"103d405d730b8de86f1c83f4aa5b31f99e1cfc04de76e48bbb4dbab54149b018","changedFields":[{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.Dns"},{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.DnsOptions"},{"actualSha256":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","expectedSha256":"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945","path":"HostConfig.DnsSearch"}],"evidence":"captured","expectedSha256":"37c24299b8eeede7707905a435e99360de08eb2a852d1f4750db353efa17c7b2","schema":"nodedc.device-core.runtime-drift-fields.v1","service":"device-control-core","truncated":false}', 'rollback_status': 'failed:DeployError', 'sha256': 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba', 'started_apply': True, 'status': 'failed'}, 'predecessor': 'device-core-release-v1-r38-dcb0c76ac8e9403c05cc64e9cdde5ebf859f2766'}
DEVICE_R46_RECON_ID = 'device-core-release-r46-reconciliation-v1-20261105-001'
DEVICE_R46_RECON_ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json'
DEVICE_DNS_FIELDS = ('Dns', 'DnsOptions', 'DnsSearch')
def device_release_fields_v3(fields):
result = device_release_mounts_v2(fields)
host = result['HostConfig']
for key in DEVICE_DNS_FIELDS:
if key not in host:
die('Device Core v3 DNS field is missing')
value = host[key]
if value is None:
host[key] = []
elif not isinstance(value, list) or any(not isinstance(v, str) for v in value):
die('Device Core v3 DNS field is malformed')
return result
def device_release_runtime_snapshot_v3():
result = {}
for service, sample in device_release_drift_sample().items():
row = dict(sample['runtime'])
if not row['running'] or row['health'] not in (None, 'healthy'):
die('Device Core predecessor service is not healthy: ' + service)
row['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(sample['fields']))
result[service] = row
return result
def device_r46_dns_proof(fields, expected):
device_release_fields_v3(fields) # Validate, without altering the v2 preimage.
candidate = device_release_mounts_v2(fields)
if not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected):
die('Device Core r46 saved digest is invalid')
if any(candidate['HostConfig'][k] not in (None, []) for k in DEVICE_DNS_FIELDS):
die('Device Core r46 proof requires empty DNS settings')
for checked, values in enumerate(itertools.product((None, []), repeat=3), 1):
for key, value in zip(DEVICE_DNS_FIELDS, values):
candidate['HostConfig'][key] = value
if device_release_drift_digest(candidate) == expected:
return checked
die('Device Core r46 runtime differs beyond empty DNS representation')
def device_r46_descriptor():
e = DEVICE_R46_EVIDENCE
return {'schemaVersion': 'nodedc.device-core.r46-reconciliation.v1',
'releaseId': DEVICE_R46_RECON_ID, 'failedReleaseId': e['failedRow']['id'],
'failedSha256': e['failedRow']['sha256'], 'backupId': e['failedRow']['backup_id'],
'runtimeFingerprintVersion': 3, 'mode': 'prove-restored-baseline-empty-dns-only',
'cmsSuccessor': e['cms'][-1]['row']['id']}
def validate_device_r46_payload(payload, entries, identity):
if tuple(entries or ()) != (DEVICE_R46_RECON_ENTRY,) or identity != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation identity/entry mismatch')
marker = payload / DEVICE_R46_RECON_ENTRY
expected = (json.dumps(device_r46_descriptor(), sort_keys=True, indent=2) + '\n').encode()
if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != expected:
die('Device Core r46 reconciliation descriptor mismatch')
def device_r46_evidence():
e = DEVICE_R46_EVIDENCE
row = e['failedRow']
records = [r for r in load_state(FAILED_STATE_FILE)
if r.get('id') == row['id'] or r.get('sha256') == row['sha256']]
if records != [row] or any(r.get('id') == row['id'] or r.get('sha256') == row['sha256']
for r in load_state(STATE_FILE)):
die('Device Core r46 failed receipt mismatch')
archive = FAILED_DIR / row['artifact']
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row['sha256']:
die('Device Core r46 failed archive mismatch')
backup = BACKUPS_DIR / row['backup_id']
if backup.is_symlink() or not backup.is_dir():
die('Device Core r46 backup is unsafe')
for name, digest in e['backupHashes'].items():
path = backup / name
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die('Device Core r46 backup digest mismatch: ' + name)
before = read_strict_json(backup / 'device-release-before.json', 'Device Core r46 backup', max_bytes=256*1024)
if before.get('runtimeFingerprintVersion') != 2 or before.get('predecessor') != e['predecessor']:
die('Device Core r46 predecessor/version mismatch')
existing = read_backup_path_list(backup / 'existing-files.txt')
missing = read_backup_path_list(backup / 'missing-files.txt')
validate_backup_partition(DEVICE_RELEASE_ENTRIES, existing, missing, 'Device Core r46 reconciliation')
if missing:
die('Device Core r46 backup partition mismatch')
with tempfile.TemporaryDirectory(prefix='device-r46-evidence-', dir=TMP_DIR) as tmp:
materialize_backup_tree(backup / 'source-before.tgz', Path(tmp), set(existing))
if collect_exact_files(Path(tmp), existing, 'Device Core r46 source backup') != before['installedFiles']:
die('Device Core r46 source/runtime evidence conflict')
return before
def device_r46_cms_evidence():
"""Read only the three exact accepted CMS successors, not arbitrary drift."""
evidence = DEVICE_R46_EVIDENCE['cms']
applied = load_state(STATE_FILE)
failed = load_state(FAILED_STATE_FILE)
backups = []
for item in evidence:
row = item['row']
if [r for r in applied if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] != [row]:
die('Device Core r46 CMS successor receipt mismatch')
if any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] for r in failed):
die('Device Core r46 CMS successor has conflicting receipt')
backup = BACKUPS_DIR / row['backup_id']
path = backup / 'cms-runtime-before.json'
if (backup.is_symlink() or not backup.is_dir() or path.is_symlink() or not path.is_file()
or sha256_file(path) != item['backupSha256']):
die('Device Core r46 CMS successor backup mismatch')
before = read_strict_json(path, 'Device Core r46 CMS backup', max_bytes=2*1024*1024)
with tempfile.TemporaryDirectory(prefix='device-r46-cms-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']:
die('Device Core r46 CMS archive identity mismatch')
descriptor = validate_cms_release_payload(payload, entries, row['id'])
if descriptor != before['descriptor']:
die('Device Core r46 CMS source/backup identity mismatch')
backups.append(before)
for previous, current in zip(backups, backups[1:]):
if (current['predecessor'] != previous['descriptor']['sourceCommit']
or current['otherServices'] != previous['otherServices']):
die('Device Core r46 CMS successor chain mismatch')
return backups
def device_r46_other_services(before, cms_backups):
# A new CMS container is permitted only after proving the exact r47/r49/r50
# chain and current r50 app bytes, health, config and all unrelated services.
latest = cms_backups[-1]
if cms_installed_release() != latest['descriptor']:
die('Device Core r46 requires the exact accepted CMS successor')
cms_healthchecks()
runtime = cms_runtime_snapshot_v2()
if (runtime['configSha256'] != latest['runtime']['configSha256']
or runtime['imageRef'] != latest['runtime']['imageRef']
or runtime['id'] == latest['runtime']['id']):
die('Device Core r46 CMS configuration/generation drift')
actual, metadata = cms_application_inventory()
if (metadata != latest['installedMetadata'] or cms_foundation() != latest['foundation']
or cms_image_files(runtime['id']) != {k: v for k, v in actual.items() if k not in CMS_DEPENDENCY_FILES}
or cms_other_services() != latest['otherServices']):
die('Device Core r46 CMS source or preserved services differ')
old_id = cms_backups[0]['runtime']['id']
saved = before['otherComposeServices']
current = device_release_other_compose_services()
if old_id not in saved or runtime['id'] not in current or old_id in current:
die('Device Core r46 CMS predecessor container identity mismatch')
unchanged = {k: v for k, v in saved.items() if k != old_id}
if (any(cms_backups[0]['otherServices'].get(k) != v for k, v in unchanged.items())
or {k: v for k, v in current.items() if k != runtime['id']} != unchanged):
die('Device Core r46 changed an unrelated Compose service')
return current
def device_r46_restored_baseline(before):
if before.get('runtimeFingerprintVersion') != 2 or set(before['runtime']) != set(DEVICE_RELEASE_INVENTORY):
die('Device Core r46 requires the exact v2 inventory')
samples = [device_release_drift_sample() for _ in range(3)]
if any(sample != samples[0] for sample in samples):
die('Device Core r46 runtime changed during reconciliation')
baseline = json.loads(json.dumps(before))
baseline['runtimeFingerprintVersion'] = 3
baseline.pop('runtimeFieldDigests', None) # Historical v2 diagnostics stay in the immutable backup.
for service in DEVICE_RELEASE_INVENTORY:
sample = samples[0][service]
row, fields, old = sample['runtime'], sample['fields'], before['runtime'][service]
if (not row['running'] or row['health'] not in (None, 'healthy') or row['imageId'] != old['imageId']
or row['runtimeConfigSha256'] != device_release_drift_digest(fields)):
die('Device Core r46 image/health/evidence mismatch: ' + service)
v2 = dict(row, runtimeConfigSha256=device_release_drift_digest(device_release_mounts_v2(fields)))
if service not in DEVICE_RELEASE_SERVICES and v2 != old:
die('Device Core r46 preserved service differs: ' + service)
device_r46_dns_proof(fields, old['runtimeConfigSha256'])
baseline['runtime'][service]['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(fields))
return baseline
def preflight_device_r46_reconciliation(payload, entries, identity, *, marker_installed=False):
require_root()
validate_device_r46_payload(payload, entries, identity)
marker = DEVICE_PLANE_ROOT / DEVICE_R46_RECON_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die('Device Core r46 marker already exists')
before = device_r46_evidence()
baseline = device_r46_restored_baseline(before)
baseline['otherComposeServices'] = device_r46_other_services(before, device_r46_cms_evidence())
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
accept_device_release(baseline, rollback=True)
print('device_r46_reconciliation=exact-v2-sha;dns-empty-only;samples=3;fingerprint=v3;'
'cms-successor=r50;services=none;build=none;runtime-mutation=none')
return baseline
def device_r46_reconciled(row):
if row != DEVICE_R46_EVIDENCE['failedRow']:
return False
records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_R46_RECON_ID]
if not records:
return False # Marker alone, including in-progress apply, grants nothing.
if (len(records) != 1 or records[0].get('component') != 'device-core-release-reconciliation'
or records[0].get('status') != 'ok'):
die('Device Core r46 reconciliation receipt mismatch')
validate_device_r46_payload(DEVICE_PLANE_ROOT, (DEVICE_R46_RECON_ENTRY,), DEVICE_R46_RECON_ID)
with tempfile.TemporaryDirectory(prefix='device-r46-marker-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
if manifest['component'] != 'device-core-release-reconciliation' or manifest['id'] != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation archive identity mismatch')
validate_device_r46_payload(payload, entries, manifest['id'])
device_r46_evidence()
device_r46_cms_evidence()
return True
# END GENERATED DEVICE R46 RECOVERY
def main(argv): def main(argv):
if argv == ["--dc-cms-autodeploy-tick"]: if argv == ["--dc-cms-autodeploy-tick"]:
return cms_autodeploy_tick() return cms_autodeploy_tick()
@@ -152,21 +152,21 @@ class MountOrderTests(unittest.TestCase):
new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40} new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40}
stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}])) stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}]))
with redirect_stdout(io.StringIO()):R.accept_device_release(new) with redirect_stdout(io.StringIO()):R.accept_device_release(new)
for version in [True,0,3,'2']: for version in [True,0,4,'2']:
with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version}) with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version})
def test_preflight_records_v2_for_new_normal_release(self): def test_preflight_records_v3_for_new_normal_release(self):
with ExitStack() as stack: with ExitStack() as stack:
for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v2',runtime())]: for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v3',runtime())]:
stack.enter_context(mock.patch.object(R,name,return_value=value)) stack.enter_context(mock.patch.object(R,name,return_value=value))
for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']: for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']:
stack.enter_context(mock.patch.object(R,name)) stack.enter_context(mock.patch.object(R,name))
legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot')) legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot'))
detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}})) detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}}))
before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id') before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id')
self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called() self.assertEqual(before['runtimeFingerprintVersion'],3);legacy.assert_not_called()
self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}}) self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}})
detail.assert_called_once_with(before['runtime']) detail.assert_called_once_with(before['runtime'],3)
def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self): def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self):
old = samples_fixture();before = evidence_fixture(old);current = reorder(old) old = samples_fixture();before = evidence_fixture(old);current = reorder(old)
@@ -0,0 +1,115 @@
"""r46 immutable evidence, v3 acceptance and marker-only runtime boundary."""
import copy
from contextlib import ExitStack
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from test_device_core_release import R, fixture, runtime
class R46EvidenceTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
def evidence(self, stack):
e = copy.deepcopy(R.DEVICE_R46_EVIDENCE)
failed, backups, source = (self.root / p for p in ('failed', 'backups', 'source'))
for p in (failed, backups, source):
p.mkdir()
fixture(source)
backup = backups / e['failedRow']['backup_id']
backup.mkdir()
entries = R.DEVICE_RELEASE_ENTRIES
before = {'runtimeFingerprintVersion': 2, 'predecessor': e['predecessor'],
'installedFiles': R.collect_exact_files(source, entries, 'fixture')}
(backup / 'device-release-before.json').write_text(json.dumps(before))
for name in ('existing-files.txt', 'files.txt'):
(backup / name).write_text('\n'.join(entries) + '\n')
(backup / 'missing-files.txt').write_text('')
(backup / 'manifest.env').write_text('fixture')
with tarfile.open(backup / 'source-before.tgz', 'w:gz') as tar:
for entry in entries:
tar.add(source / entry, arcname=entry)
archive = failed / e['failedRow']['artifact']
archive.write_bytes(b'exact failed archive')
e['failedRow']['sha256'] = R.sha256_file(archive)
e['backupHashes'] = {p.name: R.sha256_file(p) for p in backup.iterdir()}
for name, value in [('DEVICE_R46_EVIDENCE', e), ('TMP_DIR', self.root),
('FAILED_DIR', failed), ('BACKUPS_DIR', backups)]:
stack.enter_context(patch.object(R, name, value))
ledger = stack.enter_context(patch.object(R, 'load_state', side_effect=lambda p: [e['failedRow']] if p == R.FAILED_STATE_FILE else []))
return e, before, backup, archive, ledger
def test_exact_receipt_backup_and_source_evidence(self):
with ExitStack() as stack:
e, before, backup, archive, ledger = self.evidence(stack)
self.assertEqual(R.device_r46_evidence(), before)
for path in [archive, *backup.iterdir()]:
old = path.read_bytes()
path.write_bytes(old + b'changed')
with self.subTest(path=path.name), self.assertRaises(R.DeployError):
R.device_r46_evidence()
path.write_bytes(old)
ledger.side_effect = lambda p: [e['failedRow']]
with self.assertRaisesRegex(R.DeployError, 'receipt mismatch'):
R.device_r46_evidence()
def test_hash_consistent_but_conflicting_backup_is_rejected(self):
with ExitStack() as stack:
e, before, backup, _, _ = self.evidence(stack)
before['installedFiles']['package.json'] = 'f' * 64
target = backup / 'device-release-before.json'
target.write_text(json.dumps(before))
e['backupHashes'][target.name] = R.sha256_file(target)
with self.assertRaisesRegex(R.DeployError, 'source/runtime evidence conflict'):
R.device_r46_evidence()
def test_v3_acceptance_preserves_images_database_topology_and_source(self):
old = runtime()
before = {'runtimeFingerprintVersion': 3, 'runtime': old, 'compose': {},
'otherComposeServices': {}, 'installedFiles': {}}
with ExitStack() as stack:
stack.enter_context(patch.object(R, 'DEVICE_PLANE_ROOT', self.root / 'live'))
for name, value in [('component_compose_files', ()), ('collect_exact_files', {}),
('device_release_other_compose_services', {}),
('validate_device_manager_control_plane_runtime', None),
('validate_installed_device_b2', None)]:
stack.enter_context(patch.object(R, name, return_value=value))
current = stack.enter_context(patch.object(R, 'device_release_runtime_snapshot_v3', return_value=old))
R.accept_device_release(before, rollback=True)
for service, key, value in [('device-manager', 'imageId', 'wrong-image'),
('device-control-core', 'runtimeConfigSha256', 'wrong-config'),
('device-postgres', 'containerId', 'recreated'),
('device-gateway', 'restartCount', 1),
('device-backhaul-target', 'containerId', 'recreated')]:
changed = copy.deepcopy(old)
changed[service][key] = value
current.return_value = changed
with self.subTest(service=service, key=key), self.assertRaises(R.DeployError):
R.accept_device_release(before, rollback=True)
current.return_value = old
with patch.object(R, 'collect_exact_files', return_value={'unexpected.js': 'sha'}), self.assertRaisesRegex(R.DeployError, 'source mismatch'):
R.accept_device_release(before, rollback=True)
with patch.object(R, 'device_release_other_compose_services', return_value={'other': {}}), self.assertRaisesRegex(R.DeployError, 'unrelated Compose'):
R.accept_device_release(before, rollback=True)
def test_marker_runtime_dispatch_has_no_build_or_restart(self):
entries = (R.DEVICE_R46_RECON_ENTRY,)
component = 'device-core-release-reconciliation'
with patch.object(R, 'run_build') as build, patch.object(R, 'run_compose') as compose, patch.object(R, 'prepare_component_runtime') as prepare:
R.run_component_runtime(component, entries, ())
build.assert_not_called()
compose.assert_not_called()
prepare.assert_not_called()
with patch.object(R, 'preflight_device_r46_reconciliation') as preflight:
R.run_healthchecks(component, entries, ())
preflight.assert_called_once_with(R.DEVICE_PLANE_ROOT, entries, R.DEVICE_R46_RECON_ID, marker_installed=True)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,75 @@
# Device Core r46: empty DNS representation
The r46 release (`e30a6dd2a1eae306d811977188f5d118aefed4ab`) failed
acceptance on 2026-11-05. Its rollback restored the accepted r38 source,
but failed the v2 configuration fingerprint. The recorded field evidence
identifies exactly `HostConfig.Dns`, `DnsOptions`, and `DnsSearch`: saved
`[]`, observed `null`. The failed artifact and original backups stay immutable.
An accessible UI and 79 matching source files alone do not prove runtime rollback.
## Registered transition
`device-core-release-reconciliation` gains one exact marker:
`deployment/device-core-release-r46-reconciliation-v1.json`, identity
`device-core-release-r46-reconciliation-v1-20261105-001`.
The live root remains `/volume1/docker/nodedc-device-plane`. The marker selects
no service, build, Compose operation, runtime mutation, database or secret.
The existing marker-only rollback removes only the newly installed marker.
The builder accepts no authority from command-line or payload metadata.
`r46-evidence.json` pins the exact failed receipt, archive, six backup files and
the successful CMS r47/r49/r50 receipts plus their immutable runtime backups.
`r46_runtime.py` is embedded in the standalone root-owned installer by
`embed_r46.py`; no code is loaded from SMB at runtime.
## Runtime proof
The recovery reads three stable observations of all five Device services.
It enumerates at most eight combinations of the three **empty** DNS fields
and must reproduce each saved whole v2 SHA exactly. No field hash substitutes
for this whole-configuration proof. Nonempty DNS settings, environment, mounts,
bind order, ports, security flags and networks cannot be changed by the proof.
Every image must equal the saved image ID. Preserved Postgres, gateway and
backhaul also retain their complete identity and state. Source, Compose,
B2 foundation, runtime boundaries and health are checked by existing acceptance.
Fingerprint v3 keeps the existing v2 mount normalization and converts only
explicit `null` values in the three DNS fields to `[]`. Missing fields and
malformed values fail closed. Nonempty lists retain every value and their
order. Historic v1/v2 fingerprints and their exact acceptance remain intact.
New normal Device releases record v3 and version-matched diagnostic hashes.
## Concurrent CMS releases
CMS legitimately replaced its container after the Device incident. Recovery
does not ignore CMS or arbitrary unrelated drift. It validates only the pinned
r47 → r49 → r50 chain, every canonical receipt/archive/backup, the current r50
source, running application bytes, configuration and health. The original CMS
container ID comes from the pinned r47 backup. Only that one old/new CMS entry
is substituted in the derived in-memory baseline. The other 61 Compose entries
must be unchanged. CMS's own preserved-service snapshot must also match.
A newer CMS successor or unexplained container change requires new review.
CMS source, sites, configuration, credentials and runtime are never written.
## Queue and operator gates
A marker alone, including an in-progress apply, grants nothing. Only a separate
successful canonical recovery receipt with the matching archived marker permits
the exact run46/run-number39/digest/source tuple to move from `blocked` to
terminal `failed`. It is never made `ready` and never retried. The next qualified
commit follows the ordinary outbound Git deployment route.
1. Review source/tests and promote the SHA-pinned root-owned installer, checking
the exact previous installer SHA and an idle deploy lock.
2. Run `verify-install` immediately from the installed path.
3. Stage the deterministic marker artifact, inspect its lifecycle, then obtain a
fresh canonical `plan`. The plan itself performs the read-only runtime proof.
4. Review the plan and apply once. `apply` repeats all proof before and after
marker installation; no application runtime changes are selected.
5. Observe the ordinary next release receipt, then check the resulting Device UI.
Tests cover integrity failures, real configuration drift, image and dependency
changes, unstable observations, unsupported versions, exact artifact scope,
CMS generation drift, historical v1/v2 compatibility, queue identity and
idempotency, marker-only runtime dispatch and Python 3.8 syntax.
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Deterministic data-only marker for the exact r46 rollback reconciliation."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json'
def bundle():
descriptor = (ROOT / 'r46-reconciliation-v1.json').read_bytes()
identity = json.loads(descriptor)['releaseId']
members = {
'manifest.env': ('id=' + identity + '\ncomponent=device-core-release-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (ENTRY + '\n').encode(),
'payload/' + ENTRY: descriptor,
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name, data in sorted(members.items()):
info = tarfile.TarInfo(name)
info.mode, info.size = 0o644, len(data)
archive.addfile(info, io.BytesIO(data))
return identity, output.getvalue()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir', required=True, type=Path)
args = parser.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
identity, data = bundle()
path = args.output_dir / ('nodedc-' + identity + '.tgz')
with path.open('xb') as stream:
stream.write(data)
print(json.dumps({'artifact': str(path), 'id': identity, 'sha256': hashlib.sha256(data).hexdigest()}))
+7
View File
@@ -8,6 +8,13 @@ class Controller:
def reconcile(self): def reconcile(self):
for row in self.queue.snapshot(): for row in self.queue.snapshot():
if row['phase'] == 'blocked':
outcome, receipt = self.installer.receipt(row)
if outcome == 'rolled-back':
self.queue.reconcile_r46(row['id'], digest=row['digest'], artifact=row['artifact'], receipt=receipt)
elif outcome != 'ambiguous':
raise QueueError('blocked_run_requires_exact_recovery')
continue
if row['phase'] != 'deploying': if row['phase'] != 'deploying':
continue continue
outcome, receipt = self.installer.receipt(row) outcome, receipt = self.installer.receipt(row)
@@ -174,5 +174,29 @@ class DeploymentQueue:
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply) self.transaction(apply)
def reconcile_r46(self, identity, *, digest, artifact, receipt):
"""Exact terminal blocked -> failed recovery after canonical proof.
This never makes the failed artifact ready again. The caller verifies
the immutable failed evidence and the separate successful recovery.
"""
sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab'
expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001'
if (type(identity) is not int or identity != 46
or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba'
or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz'
or receipt != expected_receipt):
raise QueueError('r46_reconciliation_identity_mismatch')
def apply():
row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone()
if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact):
raise QueueError('r46_reconciliation_row_mismatch')
if row['phase'] == 'failed' and row['receipt'] == receipt:
return
if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed':
raise QueueError('r46_reconciliation_predecessor_mismatch')
self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity))
self.transaction(apply)
def snapshot(self): def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")] return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
+24
View File
@@ -0,0 +1,24 @@
"""Embed the reviewed r46 recovery into the standalone root-owned runner."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent
RUNNER = ROOT.parent / 'deploy-runner/nodedc-deploy'
START = '# BEGIN GENERATED DEVICE R46 RECOVERY\n'
END = '# END GENERATED DEVICE R46 RECOVERY\n'
def section():
source = (ROOT / 'r46_runtime.py').read_text()
evidence = json.loads((ROOT / 'r46-evidence.json').read_text())
return START + source.replace('__DEVICE_R46_EVIDENCE__', repr(evidence)) + '\n' + END
if __name__ == '__main__':
current = RUNNER.read_text()
if START in current:
before, rest = current.split(START, 1)
_, after = rest.split(END, 1)
current = before + section() + after
else:
current = current.replace('\ndef main(argv):', '\n' + section() + '\n\ndef main(argv):', 1)
RUNNER.write_text(current)
@@ -0,0 +1,61 @@
{
"backupHashes": {
"device-release-before.json": "52927379518030d1e979d897e5cb298481d81a78fb694c5ab68896bfeb8a64d4",
"existing-files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a",
"files.txt": "4d02728c991e4666425d968497d3540ad95802de055db4f899411ce34e526b5a",
"manifest.env": "c126a1df2b28d0474e80727e5716311ea6b9aa5702f6b76e9d4742205d87ba62",
"missing-files.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"source-before.tgz": "dc40d86d52be8f7e02fb7ec0928da371e37f813676bba182fb883212cc7ec967"
},
"cms": [
{
"backupSha256": "1156f7bdc0313cb4ad8f2541cbe260e965784201b18baacb548480ee6add902d",
"row": {
"applied_at": "2026-11-05T10:32:58+00:00",
"artifact": "nodedc-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1-20261105-133137",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r47-aff551e4d437dced1114fc505443c484c9d275f1",
"sha256": "dfd7bbc8753af8b6693253a5a7030995fc6745e541e5206ca1e708bf17555a5d",
"status": "ok"
}
},
{
"backupSha256": "6a800c80d6cd533bf7d31745baa20ab9912ac9c93f1e9febbe19a61006650547",
"row": {
"applied_at": "2026-11-05T10:35:39+00:00",
"artifact": "nodedc-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835-20261105-133344",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r49-99b9222735b1d473d15811e390f048669ef36835",
"sha256": "d69852e99b251310bc96ec88dcc89d9d16ca704c49f35d8a168c2835440652b0",
"status": "ok"
}
},
{
"backupSha256": "2b96d060d5aee54998dabb1c432fe495469cebc92a59b859ff00a0c1183690ca",
"row": {
"applied_at": "2026-11-05T10:54:15+00:00",
"artifact": "nodedc-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3.tgz",
"backup_id": "dc-cms-release-dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3-20261105-135303",
"component": "dc-cms-release",
"id": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3",
"sha256": "88a09153b860280c0a28c51e13bbe8d68cb39e7030ce2ba70bc9a0bf8a367c43",
"status": "ok"
}
}
],
"failedRow": {
"artifact": "nodedc-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab.tgz.20261105-132438",
"backup_id": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438",
"component": "device-core-release",
"failed_at": "2026-11-05T10:30:32+00:00",
"id": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab",
"message": "Device Core release runtime configuration drift: device-control-core; field_evidence={\"actualSha256\":\"103d405d730b8de86f1c83f4aa5b31f99e1cfc04de76e48bbb4dbab54149b018\",\"changedFields\":[{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.Dns\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsOptions\"},{\"actualSha256\":\"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b\",\"expectedSha256\":\"4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945\",\"path\":\"HostConfig.DnsSearch\"}],\"evidence\":\"captured\",\"expectedSha256\":\"37c24299b8eeede7707905a435e99360de08eb2a852d1f4750db353efa17c7b2\",\"schema\":\"nodedc.device-core.runtime-drift-fields.v1\",\"service\":\"device-control-core\",\"truncated\":false}",
"rollback_status": "failed:DeployError",
"sha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba",
"started_apply": true,
"status": "failed"
},
"predecessor": "device-core-release-v1-r38-dcb0c76ac8e9403c05cc64e9cdde5ebf859f2766"
}
@@ -0,0 +1,10 @@
{
"backupId": "device-core-release-device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab-20261105-132438",
"cmsSuccessor": "dc-cms-release-v1-r50-164499f0bbc4222320d554e89bce19161477d4a3",
"failedReleaseId": "device-core-release-v1-r46-e30a6dd2a1eae306d811977188f5d118aefed4ab",
"failedSha256": "b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba",
"mode": "prove-restored-baseline-empty-dns-only",
"releaseId": "device-core-release-r46-reconciliation-v1-20261105-001",
"runtimeFingerprintVersion": 3,
"schemaVersion": "nodedc.device-core.r46-reconciliation.v1"
}
+221
View File
@@ -0,0 +1,221 @@
"""Versioned DNS representation fingerprint and exact r46 evidence-only recovery.
Embedded into the root-owned runner. No production code is imported from SMB.
Historical v1/v2 hashes are never reinterpreted without an exact preimage proof.
"""
DEVICE_R46_EVIDENCE = __DEVICE_R46_EVIDENCE__
DEVICE_R46_RECON_ID = 'device-core-release-r46-reconciliation-v1-20261105-001'
DEVICE_R46_RECON_ENTRY = 'deployment/device-core-release-r46-reconciliation-v1.json'
DEVICE_DNS_FIELDS = ('Dns', 'DnsOptions', 'DnsSearch')
def device_release_fields_v3(fields):
result = device_release_mounts_v2(fields)
host = result['HostConfig']
for key in DEVICE_DNS_FIELDS:
if key not in host:
die('Device Core v3 DNS field is missing')
value = host[key]
if value is None:
host[key] = []
elif not isinstance(value, list) or any(not isinstance(v, str) for v in value):
die('Device Core v3 DNS field is malformed')
return result
def device_release_runtime_snapshot_v3():
result = {}
for service, sample in device_release_drift_sample().items():
row = dict(sample['runtime'])
if not row['running'] or row['health'] not in (None, 'healthy'):
die('Device Core predecessor service is not healthy: ' + service)
row['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(sample['fields']))
result[service] = row
return result
def device_r46_dns_proof(fields, expected):
device_release_fields_v3(fields) # Validate, without altering the v2 preimage.
candidate = device_release_mounts_v2(fields)
if not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected):
die('Device Core r46 saved digest is invalid')
if any(candidate['HostConfig'][k] not in (None, []) for k in DEVICE_DNS_FIELDS):
die('Device Core r46 proof requires empty DNS settings')
for checked, values in enumerate(itertools.product((None, []), repeat=3), 1):
for key, value in zip(DEVICE_DNS_FIELDS, values):
candidate['HostConfig'][key] = value
if device_release_drift_digest(candidate) == expected:
return checked
die('Device Core r46 runtime differs beyond empty DNS representation')
def device_r46_descriptor():
e = DEVICE_R46_EVIDENCE
return {'schemaVersion': 'nodedc.device-core.r46-reconciliation.v1',
'releaseId': DEVICE_R46_RECON_ID, 'failedReleaseId': e['failedRow']['id'],
'failedSha256': e['failedRow']['sha256'], 'backupId': e['failedRow']['backup_id'],
'runtimeFingerprintVersion': 3, 'mode': 'prove-restored-baseline-empty-dns-only',
'cmsSuccessor': e['cms'][-1]['row']['id']}
def validate_device_r46_payload(payload, entries, identity):
if tuple(entries or ()) != (DEVICE_R46_RECON_ENTRY,) or identity != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation identity/entry mismatch')
marker = payload / DEVICE_R46_RECON_ENTRY
expected = (json.dumps(device_r46_descriptor(), sort_keys=True, indent=2) + '\n').encode()
if marker.is_symlink() or not marker.is_file() or marker.read_bytes() != expected:
die('Device Core r46 reconciliation descriptor mismatch')
def device_r46_evidence():
e = DEVICE_R46_EVIDENCE
row = e['failedRow']
records = [r for r in load_state(FAILED_STATE_FILE)
if r.get('id') == row['id'] or r.get('sha256') == row['sha256']]
if records != [row] or any(r.get('id') == row['id'] or r.get('sha256') == row['sha256']
for r in load_state(STATE_FILE)):
die('Device Core r46 failed receipt mismatch')
archive = FAILED_DIR / row['artifact']
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row['sha256']:
die('Device Core r46 failed archive mismatch')
backup = BACKUPS_DIR / row['backup_id']
if backup.is_symlink() or not backup.is_dir():
die('Device Core r46 backup is unsafe')
for name, digest in e['backupHashes'].items():
path = backup / name
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die('Device Core r46 backup digest mismatch: ' + name)
before = read_strict_json(backup / 'device-release-before.json', 'Device Core r46 backup', max_bytes=256*1024)
if before.get('runtimeFingerprintVersion') != 2 or before.get('predecessor') != e['predecessor']:
die('Device Core r46 predecessor/version mismatch')
existing = read_backup_path_list(backup / 'existing-files.txt')
missing = read_backup_path_list(backup / 'missing-files.txt')
validate_backup_partition(DEVICE_RELEASE_ENTRIES, existing, missing, 'Device Core r46 reconciliation')
if missing:
die('Device Core r46 backup partition mismatch')
with tempfile.TemporaryDirectory(prefix='device-r46-evidence-', dir=TMP_DIR) as tmp:
materialize_backup_tree(backup / 'source-before.tgz', Path(tmp), set(existing))
if collect_exact_files(Path(tmp), existing, 'Device Core r46 source backup') != before['installedFiles']:
die('Device Core r46 source/runtime evidence conflict')
return before
def device_r46_cms_evidence():
"""Read only the three exact accepted CMS successors, not arbitrary drift."""
evidence = DEVICE_R46_EVIDENCE['cms']
applied = load_state(STATE_FILE)
failed = load_state(FAILED_STATE_FILE)
backups = []
for item in evidence:
row = item['row']
if [r for r in applied if r.get('id') == row['id'] or r.get('sha256') == row['sha256']] != [row]:
die('Device Core r46 CMS successor receipt mismatch')
if any(r.get('id') == row['id'] or r.get('sha256') == row['sha256'] for r in failed):
die('Device Core r46 CMS successor has conflicting receipt')
backup = BACKUPS_DIR / row['backup_id']
path = backup / 'cms-runtime-before.json'
if (backup.is_symlink() or not backup.is_dir() or path.is_symlink() or not path.is_file()
or sha256_file(path) != item['backupSha256']):
die('Device Core r46 CMS successor backup mismatch')
before = read_strict_json(path, 'Device Core r46 CMS backup', max_bytes=2*1024*1024)
with tempfile.TemporaryDirectory(prefix='device-r46-cms-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest['component'] != 'dc-cms-release' or manifest['id'] != row['id']:
die('Device Core r46 CMS archive identity mismatch')
descriptor = validate_cms_release_payload(payload, entries, row['id'])
if descriptor != before['descriptor']:
die('Device Core r46 CMS source/backup identity mismatch')
backups.append(before)
for previous, current in zip(backups, backups[1:]):
if (current['predecessor'] != previous['descriptor']['sourceCommit']
or current['otherServices'] != previous['otherServices']):
die('Device Core r46 CMS successor chain mismatch')
return backups
def device_r46_other_services(before, cms_backups):
# A new CMS container is permitted only after proving the exact r47/r49/r50
# chain and current r50 app bytes, health, config and all unrelated services.
latest = cms_backups[-1]
if cms_installed_release() != latest['descriptor']:
die('Device Core r46 requires the exact accepted CMS successor')
cms_healthchecks()
runtime = cms_runtime_snapshot_v2()
if (runtime['configSha256'] != latest['runtime']['configSha256']
or runtime['imageRef'] != latest['runtime']['imageRef']
or runtime['id'] == latest['runtime']['id']):
die('Device Core r46 CMS configuration/generation drift')
actual, metadata = cms_application_inventory()
if (metadata != latest['installedMetadata'] or cms_foundation() != latest['foundation']
or cms_image_files(runtime['id']) != {k: v for k, v in actual.items() if k not in CMS_DEPENDENCY_FILES}
or cms_other_services() != latest['otherServices']):
die('Device Core r46 CMS source or preserved services differ')
old_id = cms_backups[0]['runtime']['id']
saved = before['otherComposeServices']
current = device_release_other_compose_services()
if old_id not in saved or runtime['id'] not in current or old_id in current:
die('Device Core r46 CMS predecessor container identity mismatch')
unchanged = {k: v for k, v in saved.items() if k != old_id}
if (any(cms_backups[0]['otherServices'].get(k) != v for k, v in unchanged.items())
or {k: v for k, v in current.items() if k != runtime['id']} != unchanged):
die('Device Core r46 changed an unrelated Compose service')
return current
def device_r46_restored_baseline(before):
if before.get('runtimeFingerprintVersion') != 2 or set(before['runtime']) != set(DEVICE_RELEASE_INVENTORY):
die('Device Core r46 requires the exact v2 inventory')
samples = [device_release_drift_sample() for _ in range(3)]
if any(sample != samples[0] for sample in samples):
die('Device Core r46 runtime changed during reconciliation')
baseline = json.loads(json.dumps(before))
baseline['runtimeFingerprintVersion'] = 3
baseline.pop('runtimeFieldDigests', None) # Historical v2 diagnostics stay in the immutable backup.
for service in DEVICE_RELEASE_INVENTORY:
sample = samples[0][service]
row, fields, old = sample['runtime'], sample['fields'], before['runtime'][service]
if (not row['running'] or row['health'] not in (None, 'healthy') or row['imageId'] != old['imageId']
or row['runtimeConfigSha256'] != device_release_drift_digest(fields)):
die('Device Core r46 image/health/evidence mismatch: ' + service)
v2 = dict(row, runtimeConfigSha256=device_release_drift_digest(device_release_mounts_v2(fields)))
if service not in DEVICE_RELEASE_SERVICES and v2 != old:
die('Device Core r46 preserved service differs: ' + service)
device_r46_dns_proof(fields, old['runtimeConfigSha256'])
baseline['runtime'][service]['runtimeConfigSha256'] = device_release_drift_digest(device_release_fields_v3(fields))
return baseline
def preflight_device_r46_reconciliation(payload, entries, identity, *, marker_installed=False):
require_root()
validate_device_r46_payload(payload, entries, identity)
marker = DEVICE_PLANE_ROOT / DEVICE_R46_RECON_ENTRY
if not marker_installed and (marker.exists() or marker.is_symlink()):
die('Device Core r46 marker already exists')
before = device_r46_evidence()
baseline = device_r46_restored_baseline(before)
baseline['otherComposeServices'] = device_r46_other_services(before, device_r46_cms_evidence())
run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES)
accept_device_release(baseline, rollback=True)
print('device_r46_reconciliation=exact-v2-sha;dns-empty-only;samples=3;fingerprint=v3;'
'cms-successor=r50;services=none;build=none;runtime-mutation=none')
return baseline
def device_r46_reconciled(row):
if row != DEVICE_R46_EVIDENCE['failedRow']:
return False
records = [r for r in load_state(STATE_FILE) if r.get('id') == DEVICE_R46_RECON_ID]
if not records:
return False # Marker alone, including in-progress apply, grants nothing.
if (len(records) != 1 or records[0].get('component') != 'device-core-release-reconciliation'
or records[0].get('status') != 'ok'):
die('Device Core r46 reconciliation receipt mismatch')
validate_device_r46_payload(DEVICE_PLANE_ROOT, (DEVICE_R46_RECON_ENTRY,), DEVICE_R46_RECON_ID)
with tempfile.TemporaryDirectory(prefix='device-r46-marker-', dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(records[0]), Path(tmp))
if manifest['component'] != 'device-core-release-reconciliation' or manifest['id'] != DEVICE_R46_RECON_ID:
die('Device Core r46 reconciliation archive identity mismatch')
validate_device_r46_payload(payload, entries, manifest['id'])
device_r46_evidence()
device_r46_cms_evidence()
return True
@@ -0,0 +1,298 @@
import ast
import copy
from contextlib import ExitStack, redirect_stdout
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
from build_r46_reconciliation import bundle
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID, WORKFLOW
from controller import Controller
from embed_r46 import section, START, END
ROOT = Path(__file__).resolve().parents[2]
RUNNER = ROOT / 'infra/deploy-runner/nodedc-deploy'
loader = importlib.machinery.SourceFileLoader('device_r46_runner', str(RUNNER))
spec = importlib.util.spec_from_loader(loader.name, loader)
r = importlib.util.module_from_spec(spec)
loader.exec_module(r)
def fields():
return {'HostConfig': {'Dns': [], 'DnsOptions': [], 'DnsSearch': [],
'Mounts': [{'Target': '/a', 'Source': '/source/a', 'Type': 'bind'},
{'Target': '/b', 'Source': '/source/b', 'Type': 'bind'}],
'Binds': ['/a:/a:ro', '/b:/b:ro'], 'NetworkMode': 'private-egress',
'ReadonlyRootfs': True, 'CapAdd': [], 'PortBindings': {}},
'Config': {'Env': ['TOKEN=fixture-do-not-log'], 'Cmd': ['node', 'server.js'], 'User': '123'},
'Mounts': [{'Source': '/source/a', 'Destination': '/a', 'RW': False}],
'networks': ['private-egress']}
def incident():
samples, runtime = {}, {}
for service in r.DEVICE_RELEASE_INVENTORY:
f = fields()
row = {'service': service, 'containerId': 'old-' + service, 'imageId': 'image-' + service,
'running': True, 'health': 'healthy', 'restartCount': 0, 'status': 'running',
'runtimeConfigSha256': r.device_release_drift_digest(r.device_release_mounts_v2(f))}
runtime[service] = copy.deepcopy(row)
if service in r.DEVICE_RELEASE_SERVICES:
row['containerId'] = 'restored-' + service
for key in r.DEVICE_DNS_FIELDS:
f['HostConfig'][key] = None
row['runtimeConfigSha256'] = r.device_release_drift_digest(f)
samples[service] = {'runtime': row, 'fields': f}
return {'runtimeFingerprintVersion': 2, 'runtime': runtime,
'installedFiles': {'app.js': 'sha'}, 'otherComposeServices': {}, 'compose': {}}, samples
class FingerprintTests(unittest.TestCase):
def test_v3_only_empty_dns_and_existing_v2_mount_order(self):
old = fields()
new = copy.deepcopy(old)
new['HostConfig']['Mounts'].reverse()
for key in r.DEVICE_DNS_FIELDS:
new['HostConfig'][key] = None
saved = copy.deepcopy(new)
self.assertNotEqual(r.device_release_mounts_v2(old), r.device_release_mounts_v2(new))
self.assertEqual(r.device_release_fields_v3(old), r.device_release_fields_v3(new))
self.assertEqual(r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old))), 8)
self.assertEqual(new, saved)
def test_nonempty_dns_order_is_preserved_not_reconciled(self):
old = fields()
for key in r.DEVICE_DNS_FIELDS:
new = copy.deepcopy(old)
new['HostConfig'][key] = ['one', 'two']
self.assertEqual(r.device_release_fields_v3(new)['HostConfig'][key], ['one', 'two'])
rev = copy.deepcopy(new)
rev['HostConfig'][key].reverse()
self.assertNotEqual(r.device_release_fields_v3(new), r.device_release_fields_v3(rev))
with self.assertRaises(r.DeployError):
r.device_r46_dns_proof(new, r.device_release_drift_digest(old))
def test_real_drift_remains_rejected(self):
old = fields()
mutations = [lambda f: f['Config'].update(Env=['TOKEN=changed']),
lambda f: f['Config'].update(Cmd=['wrong']),
lambda f: f['HostConfig'].update(NetworkMode='host'),
lambda f: f['HostConfig'].update(ReadonlyRootfs=False),
lambda f: f['HostConfig'].update(CapAdd=['SYS_ADMIN']),
lambda f: f['HostConfig'].update(PortBindings={'80/tcp': []}),
lambda f: f['HostConfig']['Binds'].reverse(),
lambda f: f['HostConfig']['Mounts'][0].update(Source='/different'),
lambda f: f['Mounts'][0].update(RW=True),
lambda f: f.update(networks=['other'])]
for mutate in mutations:
new = copy.deepcopy(old)
mutate(new)
with self.subTest(mutate=mutate), self.assertRaises(r.DeployError):
r.device_r46_dns_proof(new, r.device_release_drift_digest(r.device_release_mounts_v2(old)))
def test_malformed_dns_and_mounts_fail_closed(self):
for key in r.DEVICE_DNS_FIELDS:
for value in ('', False, 0, {}, [1], [None]):
f = fields()
f['HostConfig'][key] = value
with self.subTest(key=key, value=value), self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
f = fields()
del f['HostConfig'][key]
with self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
f = fields()
f['HostConfig']['Mounts'][1]['Target'] = '/a'
with self.assertRaises(r.DeployError):
r.device_release_fields_v3(f)
def test_stable_exact_old_images_and_preserved_services(self):
before, samples = incident()
saved = copy.deepcopy(before)
with patch.object(r, 'device_release_drift_sample', return_value=samples) as read:
baseline = r.device_r46_restored_baseline(before)
self.assertEqual(read.call_count, 3)
self.assertEqual(before, saved)
self.assertEqual(baseline['runtimeFingerprintVersion'], 3)
for service in r.DEVICE_RELEASE_INVENTORY:
self.assertEqual(baseline['runtime'][service]['imageId'], before['runtime'][service]['imageId'])
self.assertEqual(baseline['installedFiles'], before['installedFiles'])
def test_unstable_unhealthy_changed_images_and_preserved_identity_rejected(self):
before, samples = incident()
service = r.DEVICE_RELEASE_SERVICES[0]
for key, value in [('imageId', 'new'), ('running', False), ('health', 'unhealthy')]:
changed = copy.deepcopy(samples)
changed[service]['runtime'][key] = value
with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
changed = copy.deepcopy(samples)
changed[service]['runtime']['containerId'] = 'unstable'
with patch.object(r, 'device_release_drift_sample', side_effect=[samples, changed, samples]), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
preserved = next(s for s in r.DEVICE_RELEASE_INVENTORY if s not in r.DEVICE_RELEASE_SERVICES)
changed = copy.deepcopy(samples)
changed[preserved]['runtime']['containerId'] = 'recreated-db'
with patch.object(r, 'device_release_drift_sample', return_value=changed), self.assertRaises(r.DeployError):
r.device_r46_restored_baseline(before)
class ArtifactTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.artifact = self.root / 'candidate.tgz'
self.artifact.write_bytes(bundle()[1])
unpack = self.root / 'unpack'
unpack.mkdir()
self.manifest, self.entries, self.payload = r.load_artifact(self.artifact, unpack)
def test_exact_deterministic_data_only_scope(self):
self.assertEqual(self.artifact.read_bytes(), bundle()[1])
self.assertEqual(self.entries, [r.DEVICE_R46_RECON_ENTRY])
component = self.manifest['component']
self.assertEqual(r.component_services(component, self.entries), ())
self.assertEqual(r.component_builds(component, self.entries), ())
self.assertEqual(r.component_compose_files(component), ())
for path in ('services/device-manager/app.js', '.env', 'deployment/other.json', 'data/db'):
with self.assertRaises(r.DeployError):
r.allowed_payload_path(component, path)
for key, value in [('runtimeFingerprintVersion', 2), ('mode', 'restart'), ('cmsSuccessor', 'other')]:
d = r.device_r46_descriptor()
d[key] = value
(self.payload / r.DEVICE_R46_RECON_ENTRY).write_text(json.dumps(d))
with self.assertRaises(r.DeployError):
r.validate_device_r46_payload(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
def test_preflight_owns_all_checks_and_no_runtime_mutation(self):
before, samples = incident()
with ExitStack() as stack:
for name, value in [('require_root', None), ('device_r46_evidence', before),
('device_release_drift_sample', samples), ('device_r46_cms_evidence', []),
('device_r46_other_services', {})]:
stack.enter_context(patch.object(r, name, return_value=value))
stack.enter_context(patch.object(r, 'DEVICE_PLANE_ROOT', self.root / 'live'))
health = stack.enter_context(patch.object(r, 'run_healthchecks'))
accept = stack.enter_context(patch.object(r, 'accept_device_release'))
mutation = stack.enter_context(patch.object(r.subprocess, 'run', side_effect=AssertionError('unexpected command')))
with redirect_stdout(io.StringIO()):
result = r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
health.assert_called_once_with('device-core-release', r.DEVICE_RELEASE_ENTRIES, r.DEVICE_RELEASE_SERVICES)
accept.assert_called_once_with(result, rollback=True)
mutation.assert_not_called()
accept.side_effect = r.DeployError('guard rejection')
with self.assertRaises(r.DeployError):
r.preflight_device_r46_reconciliation(self.payload, self.entries, r.DEVICE_R46_RECON_ID)
def test_marker_without_success_receipt_never_releases_queue(self):
row = r.DEVICE_R46_EVIDENCE['failedRow']
with patch.object(r, 'load_state', return_value=[]):
self.assertFalse(r.device_r46_reconciled(row))
with patch.object(r, 'load_state', return_value=[{'id': r.DEVICE_R46_RECON_ID, 'status': 'failed'}]), self.assertRaises(r.DeployError):
r.device_r46_reconciled(row)
self.assertFalse(r.device_r46_reconciled({**row, 'sha256': 'a' * 64}))
def test_registered_routes_and_embedded_source_are_current(self):
source = RUNNER.read_text()
self.assertEqual(source.split(START, 1)[1].split(END, 1)[0], section().split(START, 1)[1].split(END, 1)[0])
ast.parse(source, feature_version=(3, 8))
self.assertIn('device_release_runtime_snapshot_v3()', source)
self.assertIn('not device_release_r5_reconciled(row) and not device_r46_reconciled(row)', source)
self.assertIn('ok:device-core-release-reconciliation-marker-only', source)
class CmsSuccessorTests(unittest.TestCase):
def fixture(self, stack):
preserved = {'stable': {'fingerprint': 'exact', 'running': True, 'startedAt': 'old'}}
old = {'old-cms': {'fingerprint': 'old'}, **preserved}
current = {'new-cms': {'fingerprint': 'new'}, **preserved}
latest = {'runtime': {'id': 'cms49', 'configSha256': 'config', 'imageRef': 'cms'},
'descriptor': {'releaseId': 'cms50'}, 'installedMetadata': {}, 'foundation': {'compose': 'sha'},
'otherServices': {**preserved, 'device': {'fingerprint': 'restored'}}}
backups = [{'runtime': {'id': 'old-cms'}, 'otherServices': latest['otherServices']}, latest]
values = {'cms_installed_release': latest['descriptor'], 'cms_healthchecks': None,
'cms_runtime_snapshot_v2': {'id': 'new-cms', 'configSha256': 'config', 'imageRef': 'cms'},
'cms_application_inventory': ({'admin/index.html': 'exact'}, {}),
'cms_foundation': latest['foundation'], 'cms_image_files': {'admin/index.html': 'exact'},
'cms_other_services': latest['otherServices'], 'device_release_other_compose_services': current}
mocks = {name: stack.enter_context(patch.object(r, name, return_value=value)) for name, value in values.items()}
return {'otherComposeServices': old}, backups, current, mocks
def test_only_exact_accepted_cms_generation_may_change(self):
with ExitStack() as stack:
before, backups, current, mocks = self.fixture(stack)
self.assertEqual(r.device_r46_other_services(before, backups), current)
self.assertIn('old-cms', before['otherComposeServices'])
mocks['device_release_other_compose_services'].return_value = {**current, 'foreign': {}}
with self.assertRaises(r.DeployError):
r.device_r46_other_services(before, backups)
def test_cms_drift_or_other_container_changes_not_ignored(self):
mutations = [('cms_installed_release', {'releaseId': 'unreviewed51'}),
('cms_image_files', {'admin/index.html': 'changed'}),
('cms_other_services', {}), ('cms_foundation', {}),
('cms_runtime_snapshot_v2', {'id': 'new-cms', 'configSha256': 'changed', 'imageRef': 'cms'}),
('cms_application_inventory', ({'admin/index.html': 'exact'}, {'unexpected': 'metadata'})),
('device_release_other_compose_services', {'new-cms': {}, 'stable': {'fingerprint': 'changed'}})]
for name, value in mutations:
with self.subTest(name=name), ExitStack() as stack:
before, backups, _, mocks = self.fixture(stack)
mocks[name].return_value = value
with self.assertRaises(r.DeployError):
r.device_r46_other_services(before, backups)
class QueueRecoveryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.q = DeploymentQueue(Path(self.tmp.name) / 'queue.db', first_run_number=1)
self.addCleanup(self.q.close)
self.sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab'
self.digest = r.DEVICE_R46_EVIDENCE['failedRow']['sha256']
self.artifact = 'nodedc-device-core-release-v1-r46-' + self.sha + '.tgz'
self.receipt = 'canonical-reconciled:' + r.DEVICE_R46_RECON_ID
run = {'id': 46, 'run_number': 39, 'run_attempt': 1, 'head_sha': self.sha,
'status': 'completed', 'conclusion': 'success', 'event': 'push', 'head_branch': 'main', 'path': WORKFLOW}
self.q.observe([run], repository=REPOSITORY, repository_id=REPOSITORY_ID)
self.q.reserve(46, digest=self.digest, artifact=self.artifact)
self.q.reconcile(46, digest=self.digest, artifact=self.artifact, outcome='ambiguous', receipt='canonical-rollback-unconfirmed')
def test_exact_blocked_to_failed_is_idempotent_never_ready(self):
for _ in range(2):
self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt)
self.assertEqual(self.q.snapshot()[0]['phase'], 'failed')
self.assertIsNone(self.q.next_ready())
def test_wrong_identity_digest_receipt_or_row_stays_blocked(self):
for values in [(47, self.digest, self.artifact, self.receipt),
(46, 'a' * 64, self.artifact, self.receipt),
(46, self.digest, self.artifact, 'canonical:unconfirmed')]:
with self.assertRaises(QueueError):
self.q.reconcile_r46(values[0], digest=values[1], artifact=values[2], receipt=values[3])
self.q.db.execute("UPDATE runs SET branch='other' WHERE id=46")
with self.assertRaises(QueueError):
self.q.reconcile_r46(46, digest=self.digest, artifact=self.artifact, receipt=self.receipt)
self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked')
def test_controller_reconciles_only_canonical_receipt(self):
installer = Mock()
controller = Controller(self.q, Mock(), installer)
installer.receipt.return_value = ('ambiguous', 'canonical-rollback-unconfirmed')
controller.reconcile()
self.assertEqual(self.q.snapshot()[0]['phase'], 'blocked')
installer.receipt.return_value = ('rolled-back', self.receipt)
controller.reconcile()
self.assertEqual(self.q.snapshot()[0]['phase'], 'failed')
installer.apply.assert_not_called()
installer.plan.assert_not_called()
if __name__ == '__main__':
unittest.main()