Files
zapret-autotune/PROGRESS.md
T
2026-10-10 16:03:17 +03:00

75 lines
26 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Прогресс реализации
Срез на **2026-10-10**. Этот файл описывает фактическое состояние кода, а не весь объём требований из `Requirements.md` и `Architecture.md`.
## Готово
- **2026-10-10 worker lifecycle acceptance:** `7b332f1` cleans only each blockcheck invocation's process group after success/failure, escalates TERM→KILL and checks live membership; target now has `CAP_KILL` for dropped-UID workers. Restored `--no-conflict-cleanup` to protect foreign processes. `23fbf6d` adds synchronized orphan/escalation and daemon-preservation regressions; `6bacca0` preserves private daemon diagnostics. Remote bootstrap qualified and applied frontend candidate 1 and exact-host GGC candidate 2 (`rr17---sn-n8v7kn7d.googlevideo.com`), committed generation 3, Player API OK. Queues 200–207 are empty; only active queue 300 remains. Recreated final image retains both groups. A controlled target-only daemon stop exposed a separate active-health timeout early-return bug; fixed with delegated, independently verified regressions in `8475934`. Old target and Xray were not modified. All new commits include Co-authored-by.
- **2026-10-10 live recovery retest:** deployed final image `8475934`, stopped only target-local zapret without changing committed config and waited for normal failure threshold/cooldown. Monitor attempted saved frontend revalidation (no new scan or tune run). Blockcheck returned TLS 1.2 timeout at 1/2, TLS 1.3 3/3; incomplete evidence was correctly rejected, but recovery restoration restarted both last-good groups. Player API returned OK, queues 200–207 were free, and next periodic probe reset consecutive failures to 0; monitor remains alive. Same-IP `142.251.156.4` curl comparisons through old SOCKS 1080 and new SOCKS 11080 returned HTTP 200 for all 12 requests (3 per TLS 1.2/1.3 per proxy). Worker lifecycle, apply, restoration and periodic monitor are runtime-verified; a fully successful fresh saved-first revalidation remains unproven because blockcheck occasionally times out despite stable proxy requests. Do not weaken 3/3 or describe this as full recovery acceptance. Dedicated target is left running with both committed groups; old container/Xray untouched.
- **2026-10-10 remote acceptance:** target image built from pinned base and started in a fresh directory/state volume; host SOCKS port `11080` was free, old container stayed untouched. Initial managed status confirmed generation `0`, `groups=none`, no active candidate IDs, and `NFQWS2_ENABLE=0`. Automated frontend scan of `youtube.com` completed with `total=4323, working=0`; candidate check produced an empty `strategies` array, recorded one failed run, and bootstrap error caused monitor/entrypoint exit. No strategy was applied. New target remains stopped with its fresh, strategy-free state preserved. This exposed that managed bootstrap should scan the actual Player API host (`www.youtube.com`) and ordinary no-candidate errors must not terminate ongoing monitoring. Updated code/tests are in progress; rerun required. Old container and Xray were not changed.
- **2026-10-10 remote retry:** scanning the correct `www.youtube.com` host still produced `working=0`. Diagnosis: scan left NFQUEUE workers 200–207 in the isolated target namespace; the subsequent `check --no-conflict-cleanup` preserved those workers and every candidate immediately failed. A manual `check` after a standalone scan confirmed the queue-conflict failure. Stopped only the new target (old target/Xray untouched), preserving its empty state. Managed recovery now opts into blockcheck conflict cleanup because it runs only after stopping zapret in the dedicated isolated namespace; ordinary CLI callers retain `--no-conflict-cleanup`. Local test/build pass; remote rerun pending.
- **2026-10-10 retry after worker-cleanup fix:** deployed commit `a762763` and recreated only the isolated target, retaining generation-0 empty strategy state. Managed `www.youtube.com` scan completed; subsequent shortlist check returned an empty `strategies` array, and the persistent monitor correctly continued into a later recovery scan instead of exiting. At the last reachable check the target was up, generation 0, no candidates, and 3 probe failures; SSH profile `dev` then disconnected during the next scan. Acceptance remains incomplete; reconnect and inspect current process/status/report before any further action. Old target and Xray remained untouched.
- **2026-10-10 diagnostic follow-up:** SSH reconnected. Existing SOCKS `127.0.0.1:1080` returned HTTP 200 for `https://www.youtube.com/`; direct host curl and fresh target SOCKS `127.0.0.1:11080` timed out, as expected with the disabled baseline. Independently ran `blockcheckw check` in a clean disposable container on the same target bridge using the existing frontend profile; it passed TLS 1.2 and TLS 1.3, 3/3 each. The default scan corpus omitted this exact profile, while `blockcheckw scan --from-file` found it on the same host in under a second. Repeated strict checks showed intermittent TLS 1.3 timeouts (one protocol 3/3 while the other fell to 1/2); the managed seed now retries the tiny exact-host corpus up to five times before falling back to the hour-long default search. Stopped only the dedicated target to end repeated full scans; its state remains generation 0 with no applied candidates. `go test ./...`, build, static deploy guard, entrypoint syntax, and diff checks pass. Deploy and remote acceptance rerun pending. Old container/Xray untouched.
- **2026-10-10 seed retry follow-up:** Repeated checks in one disposable namespace confirmed intermittent TLS 1.3 timeouts persist across attempts. Managed seed was changed to run `blockcheckw check` directly (not a scan that leaves NFQUEUE workers), retrying only the small seed; identical TLS 1.2/TLS 1.3 args are now de-duplicated before combined revalidation. The previous five-attempt seed-scan build is stopped; dedicated target state still has no committed candidates. Local tests/build/static checks pass; deploy and runtime verification of the direct-check seed remain pending. Old target/Xray untouched.
- **2026-10-10 latest runtime check:** Deployed the direct-check seed build. It still fell through to the default full scan; process inspection showed a seed `nfqws2` worker holding queue 200 alongside the scan's workers on 201–207. This confirms managed checks leak workers into the target namespace, so retries/default scan can contend on NFQUEUE even though a clean disposable check can pass. Stopped only the managed target; verified it is exited while the old target remains up and the existing SOCKS still returns HTTP 200. Generation remains 0 with no candidates. Next fix must explicitly clean up only blockcheck-owned NFQWS workers before retry/scan checks, then rerun acceptance. Acceptance remains incomplete.
- Added `managed monitor` and supervision only in the dedicated target entrypoint: guarded target-owned DB/identity before singleton, policy 5m/3/30m with bounded CLI/env validation, owned-loopback Player API probe/discovery without direct fallback, fixed blockcheck/zapret argv with context cancellation/join. Startup bootstraps only without a qualified active frontend, tries saved scenarios first, then scans; unresolved GGC keeps monitoring; safety/DB errors stop it. SIGTERM waits for monitor restoration before stopping target-local zapret/SS. Local fake CLI/entrypoint tests are present.
- Hardened managed recovery artifacts: общий `revalidateCandidate` удаляет старый combined JSON перед каждым check, remove errors/missing/malformed report fail closed; scan shortlist проверяется на regular file и mtime не раньше whole-second scan start (production использует unique temp path). Добавлены fake-only regression tests stale/missing shortlist, stale combined, remove failure и infrastructure classification/restoration. Tests/build/network не запускались; verification deferred orchestrator, CLI/entrypoint не добавлены.
- Добавлен injected `recoverManagedTarget` и callback wiring к persisted monitor: frontend bootstrap через scan/check/save/transaction, saved-first qualified IDs (до 10), strict valid non-pass fallback, target-local downtime и bounded restoration, frontend-only rollback boundary перед fresh exact-host GGC revalidation/scan. GGC failure отдельно unresolved, Player API не playback. Immutable candidates/committed IDs сохраняются; cleanup/rollback failure fatal. Fake-only tests добавлены; producer не запускал tests/build/network, verification deferred orchestrator. CLI/entrypoint/live runtime не подключены; старый target и Xray не менялись.
- Добавлены только reusable recovery building blocks: `listQualifiedCandidates` (known groups, newest-first, limit 1–10, shared qualification rule) и injected exact-endpoint revalidation сохранённых args. Только полный валидный two-TLS 3-pass nonpass даёт `errCandidateNonpass`; malformed/incomplete evidence, scope/args mismatch и infrastructure failures fail closed. Definitions/evidence не меняются, fresh GGC остаётся exact-host. Existing proposal recovery использует общий revalidator; managed recovery adapter, monitor CLI/entrypoint и remote calls не добавлены. Focused local-fixture tests добавлены; producer tests/build/network не запускал, verification отложена orchestrator.
- Group-wise managed activation: один или оба qualified frontend/exact-GGC candidate; full desired set (не patch), frontend-only bootstrap до Player API/GGC discovery. Journal v2 сохраняет committed/pending IDs вместе с hash; rollback/crash возвращает прежний список. `managed status` и JSON `managed active-ids` проверяют IDs/groups через DB и exact rendered hash; missing groups явно unresolved. Legacy v1 сохраняет deployment по exact hash без выдуманных IDs; unknown IDs fail closed для supervisor. Player API OK не означает GGC/video playback или full-profile health. Focused tests обновлены/добавлены; tests/build/network отложены orchestrator. Recovery callback, remote apply, текущий target и Xray не менялись.
- Добавлен internal `runManagedMonitor(ctx, deps)`: immediate/periodic probe, durable streak/reset, threshold/cooldown recovery через injected callbacks, cooldown от completion при любом результате, fatal DB/lock/finalization errors и cancellable wait. Shared runtime guards выполняются до lifetime nonblocking `flock` в target-owned directory. Одноразовая startup reconciliation под singleton использует schema-v5 PID/starttime API: exact lease снимается только при доказанном dead/PID-reused owner и запускает crash cooldown; live owner остаётся busy, legacy/unverifiable owner — fail closed. Fake-time unit-тесты scheduler core, reset/cooldown, reopen, concurrent start, cancellation и DB/finalization failures добавлены; tests/build/network не запускались в этом increment — verification отложена orchestrator. Actual recovery adapter/monitor command/entrypoint wiring и развёрнутый live target пока отсутствуют; deploy, контейнер и Xray не затронуты.
- Добавлены `Dockerfile.target`, ordered target entrypoint и `deploy/managed-target/compose.yaml`: pinned runtime digest, отдельная bridge-сеть, `cap_drop: ALL` и только `NET_ADMIN`, `NET_RAW`, `SETUID`, `SETGID` (nft/NFQUEUE, raw send и смена UID/GID nfqws2), новый private bind `./target-state`, отдельный gitignored `.env`, SOCKS TCP/UDP только на host loopback (default 11080), внутренний health proxy 1080; SS port не опубликован. Startup: ss-server/ss-local → listener → managed init (status при recreation) → zapret2 start; shutdown ограничен target-local процессами/firewall. Только deployment definition и process supervision, не autonomous monitor/recovery. Compose config/tests/build/pull/run/remote producer не выполнял; проверка отложена orchestrator, runtime gates открыты.
- Усилен guarded manual CLI `managed init|status|apply`: exact role `managed-test`, fixed ID `zapret-autotune-managed-v1`, provisioned runtime marker/base executables и private dedicated mountpoint `/var/lib/zapret-autotune/target` обязательны для всех команд. `ZAPRET_CONFIG` допускает только `/var/lib/zapret-autotune/target/config`; standalone full config разрешён только в новом target-owned volume, не поверх существующего service config (include fragments не реализованы). Proxy обязан совпадать с `socks5://127.0.0.1:$SOCKS_PORT`; проверяется ownership listening socket процессом `ss-local`. Старый контейнер/произвольный каталог/loopback proxy не проходят guards. Добавлены injected unit-тесты отказов и fresh-target success; transaction engine и shell config safety не изменены. Tests/build/network этого increment отложены producer; контейнер, deploy, remote и Xray не затронуты, image/config-loading compatibility ещё не доказана.
- Добавлена foundation schema v4 и owner identity schema v5: durable policy state по stable service ID, last probe/streak, recovery lock и cooldown. Операции с injected time атомарно записывают probe и захватывают recovery только при threshold/истёкшем cooldown/свободном lock; завершение требует точный ownership token и запускает cooldown от completion time. Stale/duplicate finish не меняет новую lease; crash сохраняет lease до PID/starttime-safe reconciliation под exclusive singleton, с новым crash cooldown. Проверка текущей v5 интеграции отложена orchestrator.
- Добавлен одноразовый `health youtube`: bounded Player API-запрос только через loopback SOCKS (`ZAPRET_AUTOTUNE_SOCKS_PROXY`, default `socks5://127.0.0.1:11080`), без ambient proxy/direct fallback. Health требует `playabilityStatus.status=OK`, не streaming URL и не playback. Config валидирует video ID (default `dQw4w9WgXcQ`), interval `5m`, failure threshold `3`, cooldown `30m`. `go test ./...`, `go build` и `git diff --check` прошли для обоих последних increments.
- Добавлена тестируемая transaction foundation для target-owned config: только квалифицированные stored candidates, separate frontend/exact-GGC profiles, versioned durable journal/backup, atomic replace, injected daemon reload + Player API post-check, rollback и crash reconciliation; external config drift fail-closed. Renderer не сохраняет wildcard GGC scope. На момент foundation CLI ещё не вызывал apply; теперь manual adapter есть, target config/runtime ещё не проверены. `go build` и повторный `go test ./...` прошли для foundation; первый test run поймал прежний flaky `TestRunBlockcheckCancellation/kill` process-state race.
- Завершён удалённый ручной GGC scan для `rr16---sn-n8v7znsz.googlevideo.com`: TLS 1.2 — 1 525 рабочих стратегий, TLS 1.3 — 800. Shortlist check нашёл 20 проходящих вариантов; точная объединённая стратегия `--lua-init=fake_default_tls=tls_mod(fake_default_tls,'rnd') --payload=tls_client_hello --lua-desync=multidisorder:pos=2,midsld:seqovl=1:seqovl_pattern=fake_default_tls --in-range=-s1 --lua-desync=oob:urp=midsld` прошла по 3/3 для TLS 1.2 и TLS 1.3. Результат относится только к указанному hostname; не означает playback/SABR и не применялся.
- Добавлена proposal-only команда `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`: discovery одного свежего exact host → qualified schema-v3 сценарии newest-first → combined TLS1.2/1.3 3/3 точных сохранённых args. Первый успешный сценарий сохраняется новым immutable candidate/run и выдаётся как NOT ACTIVE без scan. Только отсутствие eligible candidates или валидные non-pass результаты разрешают обычный scan на уже найденном host; infrastructure/malformed-report ошибки fail closed. Apply/monitor и удалённый scan не затронуты.
- Unit-тесты recovery порядка, fresh-host scope, short-circuit, fallback и fail-closed ошибок прошли; локальные `go test ./...`, `go build` и `git diff --check` успешны.
- CLI на Go: `tune youtube`, `tune googlevideo --video-id ID --proxy socks5://HOST:PORT`, `recover googlevideo --video-id ID --proxy socks5://HOST:PORT`, `discover youtube`, `health youtube`, `status`, `history`, `strategies youtube`, `render`, `managed init|status|apply|monitor`. `check youtube` пока намеренно отказывает; managed activation/monitor только внутри designated target, rollback автоматический; command/entrypoint интегрированы, runtime verification отложена.
- Proposal-only GGC pipeline: Android 21.02.35 discovery через явный proxy → scan TLS1.2/1.3 только одного найденного hostname → data-transfer shortlist (`--take 10 --passes 3`) → проверка точной комбинации 3/3 на обоих TLS → один инертный профиль с exact-host фильтром. Ранжирование по blockcheckw, не Selectel. SQLite v3 атомарно сохраняет googlevideo candidate и оба endpoint×TLS evidence; отдельный additive journal сохраняет failed runs. `history` и `strategies youtube` показывают точный endpoint/group; `status` пока относится только к frontend journal.
- Добавлены injectable unit-тесты GGC success/order/scope/filter/persistence, обязательных флагов, discovery failure, неполной/неуспешной combined проверки и fail-closed DB. После исправления exact-host фильтра `go test ./...`, `go build` и `git diff --check` прошли локально. Полный новый `tune googlevideo` ещё не прогонялся удалённо.
- `tune youtube` сканирует frontend `youtube.com`, проверяет shortlist через `blockcheckw` и выдаёт один TLS-профиль только после совместной проверки TLS 1.2 и 1.3 по 3/3. Это предложение конфигурации, оно ничего не применяет.
- SQLite без CGO: миграции до схемы v3, атомарное сохранение успешных/неуспешных tune-запусков, SHA-256 fingerprint нормализованных аргументов, `status`, read-only `history` и список предложенных стратегий. v3 добавляет неизменяемые определения кандидатов и evidence по endpoint/protocol без active-состояния; старые предложения не переносятся в кандидаты. База и каталоги создаются с ограниченными правами.
- `discover youtube --video-id ID --proxy socks5://HOST:PORT` делает запрос к YouTube Android Player API, валидирует `serverAbrStreamingUrl` и выдаёт только hostname из `googlevideo.com`; подписанный URL не выводится.
- Проверки кода после последних изменений: локальные `go test ./...` и `go build` прошли. Docker build проходил после добавления SQLite-зависимости и исправления `.dockerignore`.
## Проверено удалённо
- Read-only инвентаризация Docker-хоста: Docker 29.8.2, kernel 6.8.0-146-generic; используемый zapret2 image `vernette/ss-zapret2:v1.0.2` доступен по digest `sha256:ba158180f27cd71a291ee521c291490374fd3fcf2f81eb1434ddfb19d35de45b`. Текущий target остаётся отдельным и нетронутым. Новую сеть/контейнер ещё не создавали.
- В этом image digest доступен `/usr/bin/blockcheckw` версии 0.9.0; это позволяет отдельно проверять его наличие/версию для нового target image, но пока не доказывает route equivalence или безопасную совместную работу scan с активным proxy.
- Ранее frontend-комбинация прошла `blockcheckw check` на `youtube.com`: TLS 1.2 — 3/3, TLS 1.3 — 3/3. Ручная проверка YouTube oEmbed через SOCKS также прошла.
- Player API-запрос через SOCKS `localhost:1080` вернул `playabilityStatus=OK` и динамический `googlevideo.com` hostname.
- На одном найденном GGC hostname текущая статическая стратегия `fakeddisorder:pos=midsld:tcp_flags_set=SYN` прошла data-transfer check 3/3 для TLS 1.2 и TLS 1.3. Frontend-комбинация на этом GGC hostname не прошла; frontend и GGC требуют отдельных профилей.
- Отдельный Selectel speedtest с SNI `googlevideo` был проверен экспериментально, но **не используется** для ранжирования: принято решение доверять TLS/data-transfer результатам `blockcheckw`.
## Выполняется сейчас
- Scan и shortlist check завершены, контейнер `zapret-autotune-googlevideo-scan` остановился с кодом 0. Проверка exact combined args прошла; `tune googlevideo` не запускался end-to-end и результаты вручную в SQLite не импортировались.
- Новый отдельный `tune googlevideo` proposal-only и не меняет frontend-only `tune youtube`; удалённый end-to-end запуск команды ещё не выполнен.
## Не готово
- Проверка реального YouTube video-transfer/SABR. Прямой GET `serverAbrStreamingUrl` возвращает `sabr.malformed_config`; hostname discovery и `blockcheckw` data-transfer checks не равны проверке воспроизведения видео.
- Guarded managed CLI/monitor интегрированы внутри designated target: transaction core, bootstrap/recovery callback и deployment definition есть, но нет proven image/runtime compatibility, выполненного container provisioning и реально запущенного managed target. Одноразовый Player API health сам не запускает live automation. Цель: новый отдельный prod-like zapret2-ss контейнер только в тестовой среде; существующий контейнер не трогать. Стабильный настраиваемый loopback SOCKS для Xray; Xray config вне scope. Перед runtime пройти route/rollback gates.
- Полный сервис из требований: YAML-конфигурация сервисов, endpoint-история/покрытие, daemon/периодический мониторинг, API/метрики и multi-service режим.
## Открытые ограничения и следующие шаги
1. Проверить новый `tune googlevideo` и `recover googlevideo` end-to-end на удалённом сервере; отдельно решить, как импортировать или переиспользовать уже полученные scan результаты без повторного перебора.
2. Воспроизводимое описание отдельного prod-like target добавлено в `deploy/managed-target`; orchestrator должен проверить Compose syntax. Build/run отложены. До запуска проверить baseline-конфиг и NFQUEUE внутри container network namespace; текущие mounts, сеть, порты и конфиг не переиспользовать.
3. Проверить готовый manual managed CLI на новом изолированном target; подтвердить shell config rendering, config binding, full firewall/daemon restart и pre/post health.
4. Проверить bootstrap/recovery callback и новую CLI/entrypoint интеграцию focused tests/build. Startup singleton reconciliation уже есть; live runtime ещё не проверен. До deployment проверить shutdown grace: bounded rollback/restoration может потребовать больше текущих 45s; Docker definition в этом increment не менялась.
5. До autonomous mode доказать safety gates из `Architecture.md`: изоляцию target, эквивалентность managed SOCKS пути, версионирование, atomic activation/rollback и crash recovery.
6. Отдельно определить реальную video/SABR-проверку и traffic budget; API health не равен playback и не обнаруживает все GGC playback failures.