Перейти к основному содержимому

S2 Reference → S3 Collector Recovery — единый план исполнения

Статус: APPROVED / EXECUTION IN PROGRESS

Точный current S3 runtime: не выводить из SHA в датированных блоках ниже. Перед любым действием читать mcp__gwptd__repo_status; все записи «S3 сейчас ...» далее являются evidence-снимками на указанную дату.

Свежий read-only снимок (2026-07-20 02:46 EEST): S3 checkout был clean на next/spec-platform@e7512368202c0aba2da36955b070d10a7fd9514c; remote тогда указывал на 77f3602 и опережал его на 21 commit. Это не публикация нового кандидата и не заменяет проверку непосредственно перед deploy. Для любой следующей операции снова читать mcp__gwptd__repo_status и применять только gwptd-next-deploy --expected-sha <exact-sha> в разрешённое окно.

Базовый incident-снимок: 2026-07-15 16:30 UTC

S3 runtime в базовом снимке: next/spec-platform@5f2a3a1

Historical functional baseline 2026-07-20 -- S3 code 47f1a66: guarded activation advanced the S3 staging runtime from d51d474 to 47f1a664c2a5dae29572d57c5934a9d7e795e687. At the time of this evidence the checkout was clean and matched origin/next/spec-platform; both gwptd-app-new and gwptd-data-api were healthy, and the MCP index committed the same SHA at exactly 16,466 points. This functional release contains two narrowly tested code fixes: interface-variant entry routing and support for probes of runtime_discovered scopes. A later documentation-only descendant may change the checkout SHA without changing this code scope; always obtain the exact live SHA through mcp__gwptd__repo_status before collecting new evidence. A real no-write S3 probe of ym.competitors_position now completes with HTTP 200; its receipt explicitly reports false for cache, collection_run, intake and ETL writes.

Public-route topology: the external root https://mp.hyp.ru/ remains the legacy S2 entrypoint and therefore redirects to /admin. The S3 new application is exposed through https://mp.hyp.ru/new*; within the S3 application container, interface_variant=new directs / to /new. These are distinct routing layers, not contradictory runtime results.

No P1B, P3, P4 or P5 gate advanced. The runtime SHA changed at this release, so P1B-3 evidence must be a new untouched natural reference plus build_all cycle on an unchanged exact runtime SHA. S2 was not touched. This supersedes the d51d474 status block below only as the current runtime statement; its dated evidence remains intact. Details: Live Evidence Update 2026-07-20 S3 Activation of 47f1a66.

Historical status supersession 2026-07-19 — S3 тогда был d51d474530051d0e7e69d6246dda934d2e8410d8, clean / in sync: guarded activation of d51d474 verified. Read-only attestation: the S3 checkout is clean and in sync at this exact SHA, gwptd-app-new and gwptd-data-api healthy, and the MCP index atomically committed the same SHA at exactly 16,456 points. The deployed range excluded Basket A2. No P1B, P3, P4 or P5 gate changed state: P1B remains not proven and P1B-3 stays NATURAL REFERENCE + BUILD EVIDENCE PENDING; P3-A/B/C stay DEPLOYED / DARK / NOT ACTIVATED; both P4 endpoints stay fix_s3; P5 stays GATES NOT STARTED. This deploy changed the runtime SHA and therefore invalidated the prior quiet-window natural-cycle proof that was accumulating on the earlier 3dff005 runtime: the next admissible P1B-3 evidence must be a fresh, untouched natural 04:30–09:15 UTC cycle on the unchanged d51d474. This supersedes the dated 3dff005/6dff3ab runtime snapshots below only as the current live SHA; their dated facts remain intact as prior evidence. Details: Live Evidence Update 2026-07-19 Guarded S3 Activation of d51d474.

Historical read-only сверка (2026-07-18 15:23 UTC) — S3 тогда был next/spec-platform@6dff3ab3e0370c9b58895656f99737ff1df4f6a5, clean: 6c1452c уже входит в deployed runtime и заменяет locking read reference producer-а на обычный SELECT, не расширяя append-only grant. Это исправляет P1B-3 reference seal path, но не создаёт terminal event задним числом: нужны следующий естественный reference slot и затем естественный build_all. P3-C уже DEPLOYED / DARK / NOT ACTIVATED: оба principal и root-only credential attested, ledger пуст, socket/unit/launcher/reconciler/cron mutation отсутствуют. Историческая P3.7 bootstrap-receipt reconciliation завершена; она не доказывает outer SIGKILL -> helper PDEATHSIG, MCP retry, canonical lock contention или controlled full deploy. Эти live-fault gates остаются открыты. Data API receipt-aware guard для YM competitors развёрнут в этом SHA: read-only authenticated canary для historical run 2924 вернул degraded, а не ok. Контейнеры gwptd-app-new и gwptd-data-api healthy; collector runtime работает из root crontab, а не из одноимённых systemd service.

Operational closure 2026-07-17 20:52 UTC — S3 сейчас bbc9c35240af6089b182c4320eef67a466dfb349: первый guarded deploy 862af84 fail-closed остановился до image replacement: P3-B verifier ошибочно требовал нулевые grants, хотя exact P3-C control-principal уже существовал. Root deadline watchdog восстановил e3e04df, byte-exact cron и MCP; 86fe892 разрешил только exact 14-grant P3-C surface, после чего guarded deploy и final history deploy завершились с healthy app/API и exact MCP receipts. gwptd-live-catalog-sync.service теперь Result=success: isolated worktree через network-disabled container launcher собрал redacted S2 snapshot 99 tables / 3 views, прошёл backend/UI/history/business checks и опубликовал automation/next-s2-live-catalog@f4c5e52. Live P2 audit повторно подтвердил 67 common, 12 extensions, 0 pending. Для закрытия stale YM incident выполнен единственный scoped production run ym.services run_id=2858: success, 1341/1341, 429=0, все 1341 raw canonical and lineage receipts sealed; historical transient catch-up failed-state сброшен без полного ручного --mp ym catch-up.

Live correction 2026-07-17 19:39 UTC — S3 сейчас e3e04dff4ca1c06f71ec52ea40dd2ca4b41a73c9: guarded deploy завершился successfully после root deadline bootstrap; transaction marker отсутствует, gwptd-app-new/gwptd-data-api healthy, /new/login и Data API health вернули 200, а MCP index atomically указывает на exact deployed SHA. gwptd-deploy-restore-deadline.timer active; P3.7 этим не закрывается, поскольку P3-C dark deploy и отдельные fault/recovery proofs ещё обязательны.

Historical read-only live-состояние (2026-07-17): S3 /opt/gwptd-analytics/repo: next/spec-platform@5a8110ed8591ebbb0c323216b87f3bdc5250f403, clean. MCP state/index-receipt.json закрепляет тот же SHA, 14 840 points (2026-07-16T20:44:06Z). GitHub origin/next/spec-platform@add40439f395d5a02bfce23cf6e88835b6024ecc опережает S3 на 11 commits и не является live runtime.

Off-protocol deploy 2026-07-17 (обновляет снимок выше) — S3 сейчас db3a907: владелец Anton явно разрешил задеплоить PR#40 вне окна полного деплоя 12:30–22:00 UTC (S3 — тестовый/staging контур, S2 — прод и независимый backstop данных; пропущенный S3-сбор восстановим, коллекторы перезапускаются ежедневно/за выходные; прод /admin на S2 не тронут). Харнесс не мог быть использован: минимальный off-window патч (ранний return 0/return в assert_safe_full_deploy_window / _assert_current_safe_full_deploy_window) сломал window-guard safety-тесты (test_deploy_failure_atomicity.py:665, test_deploy_restore_deadline.py:191) → красный CI → деплой-job (needs:[test]) заблокирован. Поэтому — прямой ручной git merge --ff-only: S3 5a8110e7553449 (PR#40) в 06:26:59 UTC, затем 7553449db3a907 (P4-мерджи 821bee6 ym + 7ac6568 ozon). Дельта 5a8110edb3a907: 0 новых SQL-миграций, data_api//app/ не менялись (контейнеры не пересобирались), root crontab коллектора не менялся. Постдеплой: контейнеры healthy (gwptd-app-new, gwptd-data-api — Up, healthy), /new/login 200, data-api /health 200. Off-window патч НЕ в проде — origin/next force-revert-нут к чистому 7553449 (коммит ae96b39 удалён), затем продвинут до db3a907; прод-код несёт нетронутый window guard. Историческая оговорка этого checkpoint: на тот момент P3.7 root-seed намеренно не выполнялся, поэтому установленный GHA wrapper оставался старой сборки (5a8110e). Последующая read-only проверка 2026-07-18 подтвердила root seed и normal bootstrap; актуальный статус и оставшийся recovery gate приведены в разделе P3.7 ниже.

Historical P3-A checkpoint (2026-07-16 17:18 UTC): next/spec-platform@8a336f3, clean, GitHub и S3 на exact SHA 8a336f33dd7cfe8a1882c4e9f5b874e0fdaf2114 после workflow 29518336839. P3-A registry/compiler развёрнут без изменения фактического расписания: root cron остаётся byte-exact. Read-only postcheck подтвердил healthy app/API, 200 на internal /new/login, clean deploy state и exact MCP receipt/marker. Controlled incremental reindex обработал 20 paths и atomically сменил active index 14 532 → 14 574 points. Ни collector, ни ETL вручную не запускались, S2 не изменялся. Последний ручной exact-principal build_all завершён 2026-07-15 19:42:49 UTC на kernel-коде c43e2e7: 15/15, hard invariant gate passed.

Последний deployed implementation checkpoint: 361845a — P1B-2 full enforcement. Workflow 29498311335 (test + deploy) success; app/API и /new healthy, root cron byte-exact, MCP same-SHA index = 13 619, три fixed lock inode и monitor principal аттестованы, direct entrypoint bypass fail-closed отказан до API/DB.

Последний deployed follow-up checkpoint: 0418c04 включает P1B-3…P1B-6 и узкий MCP guard 197563a. Workflow 29507928342 прошёл полный CI и controlled deploy. S3 attested: clean checkout, byte-exact root cron, отсутствие transaction/failure/preimage state, healthy app/API, 200 на internal/public /new/login и exact MCP receipt/marker на 0418c04. Deploy incremental reindex обработал 7 paths, atomically сменил alias 14 430 → 14 432 points и закончил committed. Миграции P1B-3/4 установлены; P1B-4 publication остаётся dark, V3_KERNEL_COHERENT_PUBLICATION по-прежнему fail-closed запрещён wrapper-ом, а live DATA_API_READ_COHERENCE_MODE=off. P1B-6 по-прежнему только test-only foundation: production runner, fault injector и activation verdict отсутствуют. Поэтому rollout не закрывает natural/live gates P1B-3…P1B-6.

Последний deployed scheduler checkpoint: 8a336f3 добавляет P3-A: typed declarative registry и fail-closed compiler для 25 job-ов. Workflow 29518336839 прошёл test+deploy; 75 ProductSpec остаются scheduled, четыре endpoint осознанно unscheduled, а digest generated cron совпадает с установленным расписанием. P3 ledger/reconciler и P3.7 watchdog этим не реализованы.

Последний P3-B dark deployment checkpoint: 83c8a51 (83c8a510…) — workflow 29528818504 success 2026-07-16 19:58 UTC. CI (including a disposable MySQL 8 SHOW CREATE job) и controlled S3 deploy прошли; postcheck подтвердил clean same-SHA checkout/MCP index 14 760, microsecond collection_run timestamps, шесть пустых ledger tables, 0 non-root direct grants и scheduler users, byte-exact root cron, healthy /new и Data API. Первый 4f3f29d deploy fail-closed откатил checkout/cron на shell arity guard; 83c8a51 добавил regression fix. Ни collector, ни ETL вручную не запускались, P3 scheduler/reconciler не активирован.

Ревизия самого плана: определяется Git SHA файла; она не подменяет runtime SHA.

Решение владельца 2026-07-15: план утверждён к непрерывному исполнению в next/spec-platform; integrator вправе менять S3, делать commits и push. S2 остаётся строго read-only oracle. Collector-runs выполняются только когда они требуются gate-ом и не конфликтуют с естественным циклом.

Текущий журнал исполнения

ФазаСтатусПроверенное состояние
P0DONESingle-writer действует; GitHub, clean S3, generated docs и MCP были сведены на 9310ae5; дальше каждый checkpoint снова доказывается отдельно
P1ADONE / DEPLOYEDExact DB contract и scoped grant live; пять temporary-table модулей прошли под gwptd_etl; ручной build_all завершён 15/15, без 1046/1044/1142
P1B-0DONE / DEPLOYED3f1f152 останавливает build на первом failed step; live-сбои storage, returns и analytics доказали, что последующие шаги не запускаются
P1B-1DEPLOYED / DARKa7e18bb: outer transaction, pinned session, savepoints, SQL guard, fail-closed cursor facade; 1052 marketplace + 144 Data API tests и disposable MySQL 8 proof green; live wrapper и root cron не позволяют activation
P1B-2DONE / DEPLOYED / LIVE PROVEN361845a развернут workflow 29498311335; exact locks/principal/cron/MCP attested, collector и kernel direct entrypoint-ы отказали до API/DB, а natural freshness cron, стартовавший под deploy lock в 12:45 UTC, завершился OK после activation в 12:58 UTC
P1B-3DEPLOYED / NATURAL REFERENCE + BUILD EVIDENCE PENDINGПолный 15-step input manifest, source-closure scanner, receipts/lineage и pre-DML incomplete/partial gate deployed. 6c1452c заменил запрещённый append-only-grant locking read в reference producer-е на обычный SELECT, сохранив terminal-slot primary-key guard. На 2026-07-19 reference attempt уже terminal success, но явные off-window deploy сменили checkout между collector-ами и kernel, поэтому build корректно отказался смешивать provenance и цикл не засчитывается. Current S3 ccecdb9 deployed через штатное Sunday window; terminal event не подделывается и ручной build не запускается. Следующее доказательство: один естественный terminal reference и build_all на неизменном SHA.
P1B-4DEPLOYED / DARK / NOT LIVE PROVENAttempt/activation receipt bind-ит exact manifest, inputs, steps, formulas и invariants в один transaction с facts; journal v6 attests full schema, restores owned empty prefixes after crash and keeps runtime/cron quarantined; coherent publication и live lost-commit proof отсутствуют
P1B-5DEPLOYED / DEFAULT-OFF / METADATA ATTESTED / NOT LIVE PROVENSnapshotAPIRoute развернут, live DATA_API_READ_COHERENCE_MODE=off. Read-only inventory 2026-07-16 из Data API container: gwptd_intake=107, gwptd_kernel=24, gwptd_monitoring=10, s20_ref=3 base tables, non-InnoDB = 0; optional s2_ref на S3 отсутствует и не засчитывается. Reviewed mode rollout и reader proof под writer contention остаются обязательными
P1B-6DEPLOYED FOUNDATION / TEST-ONLY / NOT A GATEProposed/unapproved policy, fail-closed evidence validator и disposable-only 14-table fingerprint observer развернуты, но не имеют production runner, numeric budget, 15-step fault execution или activation verdict. 2026-07-18 локальный synthetic harness был отвергнут и удалён: loopback DSN мог указывать на SSH-tunnel к remote MySQL, а hand-written updates не доказывают real ETL/fault boundaries.
P1BIMPLEMENTATION IN PROGRESS / NOT ACTIVATEDP1B-2 действует live; complete manifest, same-transaction activation receipt, lost-commit reconciliation, reader coherence и performance/fault gates остаются отдельными следующими gates
P2DONE / STATIC CONTRACT ATTESTATION PROVEN76fbf0c довёл read-only S2 snapshot master@8dedd247 до 67/67 final common dispositions и 12 explicit S3 extensions. Каждая common row bind-ится к exact S2 file SHA, current S3 contract SHA и 14 review surfaces; current S3 audit подтверждает review_pending=0, review_attested_common=67, p2_gate_closed=true. 2026-07-18 три WB emptyPayloadPaths re-attested as intentional S3 safety differences (4a8611f5…, 198267cd…, 013cfe97…), not hidden from digest. Статус fix_s3 честно сохраняет S3-only natural canary обязательством P4; P2 не выдаёт эти canary за выполненные.
P3.7HISTORICAL BOOTSTRAP-RECEIPT RECOVERY COMPLETE / LIVE FAULT PROOF PENDINGRoot dispatcher provisioned from 8a4c9ad and normal bootstrap receipt from e3e04d are present on S3. At b5bc832 their compatible stale baseline was reconciled without replacing guard files; current 6dff3ab retains the verified state. Exact installed hashes, root-only wrapper policy, no-drop-in persistent timer, 0660 locks, absent transaction/stage and healthy runtime were read-only attested. Local non-root Linux regression covers outer SIGKILL -> helper PDEATHSIG and fail-closed unproven state; a separate two-process test now proves the local canonical flock order. Neither is a live crash proof. MCP transient retry, live lock contention and a next controlled full deploy remain mandatory; P3 is not closed.
P3-A (registry/compiler)DEPLOYED / STATIC PROVEN / NO SCHEDULE MUTATION8a336f3, workflow 29518336839: schedules/s3-next.yaml описывает ровно 25 typed jobs; compiler fail-closed фиксирует exact runner, endpointSet, completion type и ordered SHELL/PATH, а committed crontab побайтно равен render-у и установленному root cron. 75 ProductSpec scheduled, четыре endpoint осознанно unscheduled. Нет cron mutation, ledger или reconciler.
P3-B (dark ledger)DEPLOYED / DARK / NOT ACTIVATED83c8a51, workflow 29528818504: exact six-table schema, activation CAS+drain, DB-clocked fencing и pre-seal source-run binding развёрнуты и attested. Таблицы пусты; non-root direct grants/scheduler users 0; нет scheduler principal, timer, reconciler или P3-specific cron mutation. Детали: P3-SCHEDULE-SLOT-LEDGER-CONTRACT.md.
P3-C (control principal/API)DEPLOYED / DARK / NOT ACTIVATEDRead-only S3 attestation 2026-07-18: deployed 8932aa7 contains candidate 86fe892; both MySQL principals exist, scheduler has only USAGE, and control has exactly the limited ledger DML plus approved source reads. schedule-control.env is root:root 0600, expected-current-user/server UUID attestation is present, journal/failure markers are absent, ledger is empty, and no socket/unit exists. No scheduler, launcher, timer, reconciler, cron mutation, generation activation, collector or ETL run was enabled. Детали: P3-SCHEDULE-CONTROL-PLANE-CONTRACT.md.
P3 (кроме 3.7)IN PROGRESS / P3-A+B+C DEPLOYED DARK / NOT ACTIVATEDDeclarative source-of-truth, durable ledger и P3-C trust split live but dark; effective scheduler privileges were attested read-only on S3. Persistent reconciler, bounded catch-up и natural proof отсутствуют, поэтому Gate P3 открыт.
P4DEPLOYED CORE + API-TRUTH HARDENING / CANARY PENDINGДоказаны два drift: Ozon Realization сдвинут на прошлые три месяца, а YM competitors обрывается после первой успешной категории. Оба требуют отдельных guarded fixes после P3, не ручного catch-up. 2026-07-17: оба фикса реализованы и задеплоены в рамках того же off-protocol ручного ff-деплоя (см. live-state выше), не как отдельный P3-controlled релиз: ozon.realization (7ac6568, monthsOffset 10 + узкий currentMonthNotFoundOk guard; collector suite 1579 passed) и ym.competitors_position (821bee6, убран stop-after-first break, теперь обходятся все eligible категории; collector suite 1573 passed). d5c3bdc additionally deploys the YM Data API guard: historic rows without a complete scope receipt return degraded, never ok; an authenticated read-only S3 canary confirmed run 2924 with exactly that state. Local Ozon realization regressions cover malformed HTTP 200 and valid fetch() stable keys (d992ec7, 10/10). Local YM regression now exercises paged discovery, generate/poll/XLSX and complete dynamic receipt (a8d2284 + bd0ff94) without global temporary files. A one-request S3 Ozon microprobe proves only access and the narrow current-month empty-state rule. Оба эндпоинта остаются fix_s3: per-endpoint Gate P4 (S3-only canary and natural scheduled run) ещё не пройден ни для одного из двух.
P5–P7GATES NOT STARTEDNatural cycle, row-level parity и burn-in не начинаются до закрытия P3/P4 gates. Local ComparisonSpec v2 contracts now exist for stocks, storage and turnover, plus strict year_month query support for a later rating contract. They do not start P6: storage is WB-only by source coverage; turnover lacks derived lineage and 28-day input-range evidence; rating remains v1 because fact_rating lacks the required lineage evidence.

Статус переводится в DONE только после указанного в соответствующей фазе gate и ссылки на воспроизводимое evidence. Наличие кода или зелёных unit-тестов само по себе не закрывает live/integration gate.

Live Evidence Update: 2026-07-18 P1B-3 Reference Barrier

  • Штатный build_all в 09:15 UTC стартовал на S3 8932aa7 после того, как все 31/31 active ProductSpec inputs стали terminal success с sealed receipt на том же runtime. Он корректно остановился до business DML с единственной причиной: reference:onec_nomenclature_ref:reference_attempt_running.
  • Read-only evidence: свежий 1С reference attempt 16cb5fd6-5a92-414b-9082-3201c0db8b7b имеет только event started (04:30:01 UTC); ни success, ни failed event не записан. gwptd_reference намеренно имеет только SELECT, INSERT на append-only reference_snapshot_attempt_event, но producer делал SELECT ... FOR UPDATE, для которого MySQL требует UPDATE. Ошибка ломала и publish, и попытку записать terminal failure, поэтому состояние оставалось fail-closed running.
  • Candidate 6c1452c заменяет этот locking read на обычный SELECT. Primary key (attempt_uuid, terminal_slot) по-прежнему запрещает два terminal events; grants не расширяются. Локально: reference/build-input tests 55 passed, trust-boundary/manifest tests 10 passed, 5 skipped. Subsequent deployment включил этот fix в current S3 ea11a23; terminal event не подделывался и ручной build_all не запускался. Исторический 04:30/09:15 result остаётся pre-fix evidence, а следующее допустимое acceptance evidence — новый natural reference, затем новый natural build_all cycle.

Live Evidence Update: 2026-07-19 Mixed-Runtime Rejection

  • Natural reference at 04:30 UTC now succeeded: attempt 3b611a9d-8140-40b6-9e36-f9c49772fb60 has started and success events on runtime aa769c50bbd160a36c1426ede9e651501a874682. Its sealed receipts are onec.nomenclature=19,549 and onec.warehouses=119; the scheduled 1C, WB, Ozon, YM and Lamoda collector runs for the same day also used aa769.
  • The 09:15 UTC kernel wrapper instead saw cfea7f513cd23fda0d1dc461eaefa34102ce94d1 and stopped before business steps with kernel build input resolution is incomplete: the candidate runtime/parser did not match the sealed source receipts. This is the intended fail-closed response; no receipt was rewritten and no manual ETL was run to manufacture acceptance evidence.
  • S3 journalctl and Git reflog show the cause: root explicitly ran gwptd-next-deploy --owner-authorized-off-window --expected-sha at 08:01, 08:26, 09:03, 09:34 and 09:40 UTC, including the cfea checkout. The normal wrapper already prevents this path: ops/bin/gwptd-next-deploy permits full deploy only at 12:30-22:00 UTC (Sunday after 14:30) and shares the runtime codebase lock with collector and ETL wrappers. This incident is an explicit operator override, not a source defect.
  • Current S3 is clean next/spec-platform@ccecdb993b2f8355677e5bf37d5a13eb8221c2de. Its guarded deployment completed after the Sunday safe window; installed and checkout deploy wrappers have the same SHA-256 and no transaction marker is present. Keep this checkout unchanged through the next 04:30-09:15 UTC natural cycle; then run the read-only P1B-3 verifier.
  • The bounded S3 access polygon is independently green: wb.balance plan mode followed by one --execute request returned HTTP 200, extracted one item and wrote no cache, collection_run, intake or ETL data. Local targeted verification is 185 passed, 5 skipped for P1B-3/deploy/probe contracts and 17 passed, 1 skipped for Weekly KPI/Data API contracts.

Live Evidence Update: 2026-07-19 Weekly KPI Contract Deploy

  • The production PageSpec route /new/test?page_code=weekly.kpi had a real UI contract mismatch: its grid exposed 100 rows while reports/weekly-kpi intentionally accepts at most 50, and its sole KPI asked for nonexistent totals.records. Commit 7b1e7b2 aligns the active GridSpec with the required [10, 25, 50] selector/default 10, restores the five requested display columns, and binds KPI tiles to weeks, models, qty and revenue. It adds API boundary and PageSpec contract tests; it changes no collector, cron, schema, ETL or S2 resource.
  • GitHub Actions run 29693999431 did not execute either hosted test job: GitHub rejected the jobs before startup because of the account billing/spending limit. This is external CI billing evidence, not a test or deploy result. In the permitted 12:30-22:00 UTC window the root-owned guarded wrapper was then invoked with exact --expected-sha 2b1bcfc5819659ecd98d17aeaae5552891bd03c8.
  • The guarded S3 transaction committed ccecdb993b2f8355677e5bf37d5a13eb8221c2de -> 2b1bcfc5819659ecd98d17aeaae5552891bd03c8. gwptd-app-new and gwptd-data-api are healthy; Data API /health returns {"status":"ok"}; the public PageSpec route correctly authenticates through /new/login; the running app image contains the corrected GridSpec/PageSpec. MCP reindex atomically committed the same SHA (16,228 points). No S2 write, manual collector, receipt rewrite or manual ETL occurred.
  • A separate bounded S3 polygon for ym.promos is green on the same runtime: exactly one POST returned HTTP 200, extracted 5 items, sampled/mapped 3, and reported cache=false, collection_run=false, intake=false, etl=false. Keep 2b1bcfc unchanged through the next natural 04:30-09:15 UTC cycle before running the P1B-3 verifier.

Live Evidence Update: 2026-07-19 S3 Staging Deploy of 3dff005

  • The only S3 runtime deployment was performed at exact SHA 3dff005c373d758d22d9b754ac7ef8baf980ad9e ("docs(collector): close F50 and F52 records"). The deployed range from the prior S3 runtime baseline 2b1bcfc includes the F-50 credentials-template completion (7e97296), the F-52 dead rate-limit cleanup (e647433), and the documentation updates that record and close the F-50 and F-52 ledger entries in this SHA. The release is not docs-only, but the deployed range changes no database schema, ETL step, collector schedule, cron line, runtime credential value, GWPTD_API_TOKENS, or S2 surface.
  • The separate repo-only documentation commit 3d5cc9d ("docs: refresh project structure counts") refreshes committed CLAUDE.md structural counters and closes the F-32 ledger entry. It is not part of this S3 runtime deploy, is not deployed to S3, and must not be claimed as an S3 runtime deployment — it lives only in this repository as a docs-only commit.
  • Local preflight passed before the deploy: scripts/docs/check-documentation.sh exited 0 (backend and UI catalogs current, documentation registry valid with 502 Markdown files, remediation history valid 63/63, business canon integrity valid); the maintained PHP documentation suite reported 12 passed, 1544 assertions; the focused Python collector suite reported 16 passed.
  • GitHub Actions run 29697173143 did not execute either hosted test job: GitHub rejected the jobs before startup because of the account billing/spending limit. This is external CI billing evidence, not a test or deploy result. In the permitted 12:30-22:00 UTC window the documented guarded manual S3 deploy was then invoked on S3 only with exact --expected-sha 3dff005c373d758d22d9b754ac7ef8baf980ad9e; both the deploy transaction and the activation verifier returned rc=0.
  • Post-deploy attestation on the new runtime: the S3 checkout under /opt/gwptd-analytics/repo is clean on the same SHA; no transaction sentinel, stage marker or failure env remains. Public https://next.mp.hyp.ru/new/login returned 200; /new/test returned 302 (auth redirect, as expected for an anonymous request); an internal Data API report endpoint returned 200 from inside the S3 network. gwptd-app-new and gwptd-data-api stayed healthy throughout.
  • S2 was not touched. No collector, ETL, receipt rewrite, manual reference attempt, manual build_all, schema migration, DB credential change or GWPTD_API_TOKENS rotation was performed.
  • This is not a P1B-3 natural-cycle proof. No new terminal reference slot and no natural 09:15 UTC build_all cycle has run on the unchanged SHA yet, so the historical P1B-3 entry above still describes the last attested state. The next admissible P1B-3 evidence remains one natural terminal reference followed by a natural build_all on the unchanged SHA 3dff005.

Live Evidence Update: 2026-07-19 Guarded S3 Activation of d51d474

  • The current S3 runtime is at exact SHA d51d474530051d0e7e69d6246dda934d2e8410d8 ("test(returns): pin canonical required-endpoint set in cycle contract"). Guarded activation was verified: read-only post-activation attestation found the S3 checkout clean and in sync on this exact SHA, gwptd-app-new and gwptd-data-api healthy, and the MCP index atomically committed the same SHA at exactly 16,456 points.
  • The deployed range from the prior 3dff005 runtime baseline excluded Basket A2. It carries UI, probe, test and new (dark) P3-D scheduler reconciler code, but adds no database schema migration, no collector-schedule or cron mutation, no runtime credential or GWPTD_API_TOKENS change, and no S2 surface change. The P3-D reconciler code it contains is present but not activated.
  • No gate advanced. This activation changed no P1B, P3, P4 or P5 state: P1B is not proven and P1B-3 remains NATURAL REFERENCE + BUILD EVIDENCE PENDING; P3-A/B/C remain DEPLOYED / DARK / NOT ACTIVATED (including the newly present reconciler code); both P4 endpoints remain fix_s3; P5 remains GATES NOT STARTED.
  • S2 was not touched. No collector, ETL, receipt rewrite, manual reference attempt, manual build_all, schema migration, DB credential change or GWPTD_API_TOKENS rotation was performed for this activation.
  • This is not a P1B-3 natural-cycle proof and it does not carry one forward. Because the deploy changed the runtime SHA, it invalidated the prior quiet-window natural-cycle proof that was accumulating on the earlier 3dff005 runtime: no new terminal reference slot and no natural 09:15 UTC build_all cycle has yet run on the unchanged d51d474. The historical 3dff005 and 6dff3ab entries above still describe their own attested states and remain intact. The next admissible P1B-3 evidence is one fresh, untouched natural terminal reference followed by a natural build_all on the unchanged SHA d51d474.

Live Evidence Update: 2026-07-20 S3 Activation of 47f1a66

  • The S3 staging runtime advanced from d51d474 to exact SHA 47f1a664c2a5dae29572d57c5934a9d7e795e687 through the normal guarded deployment wrapper. Read-only post-activation attestation found the checkout clean and in sync with origin/next/spec-platform, gwptd-app-new and gwptd-data-api healthy, and the MCP index committed at the identical SHA with 16,466 points.
  • The release scope is deliberately small: variant-aware root and auto-login entry routing, a probe fix for collectors with runtime_discovered scopes, and documentation. Local verification before activation: 18 endpoint-probe tests passed; PHP lint passed for both changed routing files; the remediation history and business-canon checks passed. No schema migration, collector schedule or cron mutation, credential change, manual collector run, manual reference attempt, or manual build_all was performed.
  • A live S3 no-write probe of ym.competitors_position executed its initial runtime-discovery request successfully with HTTP 200. Its receipt declared false for cache, collection_run, intake and ETL writes. This proves that the former pre-network configRef probe failure is fixed; it is not a natural collector-slot result and does not prove quota coverage or a P4 run.
  • Public https://mp.hyp.ru/new and /new/weekly-kpi-api return the expected SSO redirect, while /new/login returns 200. The public host root / remains the S2 legacy entrypoint and redirects to /admin; direct routing inside the S3 new-application container correctly sends / to /new when interface_variant=new. The difference is intended deployment topology.
  • No gate advanced. P1B remains unproven; P1B-3 remains NATURAL REFERENCE + BUILD EVIDENCE PENDING; P3 remains dark/not activated; P4 endpoints remain fix_s3; and P5 remains GATES NOT STARTED. Since the activation changed the runtime SHA, the next admissible P1B-3 evidence is one fresh, untouched natural terminal reference followed by natural build_all on unchanged 47f1a66. S2 was not touched.

1. Утверждённое решение владельца

Владелец утвердил последовательность ниже и назначил эту сессию единственным integrator-ом. Работа идёт по gate-ам; незакрытая фаза не подменяется ручным catch-up или общим зелёным status/count.

Утверждённая последовательность:

  1. заморозить несвязанные рефакторинги, Matrix, Qdrant и расширение платформы;
  2. первым исправить доказанный разрыв DB-контракта kernel;
  3. затем автоматически сравнить 67 общих endpoint'ов S2 и S3 на уровне запроса, окна, пагинации, parser-а и business key;
  4. отдельно устранить потерю cron-слотов;
  5. исправлять только доказанные endpoint-drift по одному;
  6. закрыть первичные, финансовые и только потом производные data-gates;
  7. считать готовность только по естественным циклам, а не по ручному catch-up.

Этот recovery-план — канонический execution-status и gate-contract именно для collector recovery P0–P7. Широкий S3-NEXT-PRODUCTION-READINESS-PLAN.md остаётся архитектурным/бэклоговым документом и не может самостоятельно продвинуть collector gate. Изменчивый статус девяти data-gates и G11 ведётся только в S3-NEXT-PARITY-REGISTER.md, допустимые отличия — только в ACCEPTED-DIFFERENCES.md, а решение о cutover — только по WAVE-7-S2-CUTOVER-RUNBOOK.md. Числа из датированного incident-снимка ниже не должны копироваться в эти реестры без sanitized artifact и отдельного обновления авторитетного документа.

2. Короткий диагноз

Фраза «коллектор S3 не работает» объединяет три разных проблемы:

  1. Доставка запусков. Долгий deploy временно снял root cron, а восстановление MCP/Qdrant затянуло quarantine. Cron не имеет durable ledger и не переигрывает уже прошедшие слоты. Поэтому одновременно протухли целые группы, хотя их API не ломались.
  2. Kernel после сбора. Исторический MySQL 1046: No database selected устранён вместе со следующими MySQL-дефектами storage, returns и analytics. Ручной exact-principal build_all на c43e2e7 прошёл 15/15. Dark outer-transaction core атомарной публикации реализован и развёрнут, но не активирован и не доказан end-to-end: P1A закрыт, P1B остаётся отдельным обязательным gate-ом.
  3. Незакрытый паритет. S3 модульнее и быстрее, но 79 ProductSpec и зелёный HTTP-run ещё не означают эквивалентность 67 контрактам S2 и девяти наборам данных.

То есть внешние API в основном доступны. Ошибка была в том, что архитектурную готовность runtime приняли за готовность замены S2 и слишком рано переключили внимание на deploy/recovery/backup вместо последовательного endpoint-by-endpoint и row-by-row доказательства.

3. Проверенные факты

3.1. S2 — рабочий read-only эталон поведения

ПараметрТекущее доказательство
Checkout/data/gwptd-analytics
Веткаmaster@8dedd247; один локальный commit сверх origin/master@cc3bc20 меняет только auth-модель, не collector
Исполняемый runtimelegacy-классы collector.py; ProductSpec на S2 фактически не выбираются, pointer-таблицы нет
Последние endpoint-состояния66 success; только намеренно отключённый wb.stocks имеет старый partial
DB leaseфактически fail-open: у runtime нет разрешения на collector_lease
Freshnessконтролирует только 23 endpoint'а, не весь каталог

Естественный цикл S2 15 июля:

UTCГруппаРезультат
03:001/1 success, 2:04
09:00WB22/22 success, 48:26
09:25Ozon18/18 success, 40:17
09:50Yandex Market18/18 success, 75:17
12:00Lamoda7/7 success, 57:55
13:10kernel build_all14/14, hard invariants green

Это доказывает доступность тех же marketplace API и даёт эталон request/window/ pagination/parser semantics. Это не делает всю архитектуру S2 образцом для копирования.

3.2. S3 — P1A работает, но весь контур ещё не готов

ПараметрТекущее доказательство
Checkout (read-only, 2026-07-17)/opt/gwptd-analytics/repo, next/spec-platform@5a8110ed8591ebbb0c323216b87f3bdc5250f403, clean; GitHub origin/next/spec-platform@add40439… ahead by 11 commits and not live
Historical P1B-2 deployGitHub Actions 29451840780: test и deploy success; transaction/failure markers отсутствовали; docs 29451843635, architecture 29451840809 и refresh 29451840783 также success
Current MCP receipttarget 5a8110ed8591ebbb0c323216b87f3bdc5250f403, 14 840 points, written 2026-07-16T20:44:06Z; прежний aa2f55c / 13 507 receipt остаётся historical evidence
Data fences/opt/mcp-gwptd/logs/etl-input-generation.lock и /opt/mcp-gwptd/logs/kernel-publication-writer.lock: root:gwptd, mode 0660, regular empty file, nlink=1, не symlink
Kernel P1Aexact-principal capability preflight green; ручной build_all 15/15; все hard invariants green
ProductSpec/pointers79/79, exact, fail-closed
Расписание75 endpoint'ов scheduled; четыре исключены точно: amazon.buybox, amazon.sales_ranks, amazon.weekly_reports, wb.stocks
Последние наступившие слоты74 endpoint'а имеют последний success; amazon.monthly_reports ещё не наступал
Lease/lockDB lease и host/codebase locks работают
Goldappleестественный run 2643 в 16:20 UTC: success, 29/29, skipped 0

Массовые freshness-alerts были следствием пропущенных групповых слотов во время deploy quarantine. Последующие S3 recovery-runs восстановили intake, но они не заменяют доказательство естественного расписания.

3.3. P1A: устранённый DB blocker и live-последовательность исправлений

В /var/log/gwptd-v3-kernel.log штатный запуск 15 июля в 09:40 UTC исторически упал на пяти temporary-table модулях:

  • fact_stocks — failed;
  • fact_storage — failed;
  • fact_orders — failed;
  • fact_returns — failed;
  • fact_analytics — failed;
  • причина у всех пяти — pymysql.err.OperationalError (1046, No database selected).

Ровно пять модулей текущего S3 создают неквалифицированные temporary tables:

  • kernel/etl/build_fact_stocks.py;
  • kernel/etl/build_fact_storage.py;
  • kernel/etl/build_fact_orders.py;
  • kernel/etl/build_fact_returns.py;
  • kernel/etl/build_fact_analytics.py.

Первичный дефект был двухзвенным:

  1. wrapper не выбирал default schema и connection layer не передавал её в PyMySQL;
  2. versioned grant-контракт gwptd_etl не содержал schema-scoped CREATE TEMPORARY TABLES.

Исполнение и доказательства:

  • 3f1f152 сделал build_all fail-fast и SQL-ошибки invariant gate fatal;
  • 9c625d1 провёл ETL-only V3_MYSQL_DATABASE=gwptd_kernel до pymysql.connect(database=...) и добавил exact identity/schema/role/grant/temp capability preflight;
  • ea7d5ff добавил grant preimage/afterimage в deploy journal и единственный owned delta CREATE TEMPORARY TABLES ON gwptd_kernel.* с ограниченным rollback;
  • 6394972 устранил MySQL 1137 в storage, материализовав exact coverage dates отдельно от current fact rows без ослабления stale-row guard;
  • 5e71c7c научил Ozon returns строго принимать оба UTC date-time формата и устранил Lamoda temporary-table self-reference через отдельный exact-key set;
  • c43e2e7 устранил 1267 в WB analytics, заменив только mixed-collation сравнение непустого derived key на числовую проверку длины.

Ручной exact-principal build на c43e2e7 последовательно прошёл stocks, storage, orders, returns, analytics, dedupe, turnover, rating и invariant gate: build_all done: all 15 steps OK. Hard invariants зелёные; отдельный soft revenue_daily_jump сообщил 8 диагностических случаев и не был замаскирован. Это закрывает P1A, но не P5: запуск был ручным, а не естественной цепочкой scheduled slot → collector → kernel → comparator.

Также это само по себе не закрывает P1B. В default production-режиме каждый cursor-контекст всё ещё коммитится отдельно; fail-fast предотвращает продолжение после ошибки, но уже завершённые ранние шаги не откатываются. a7e18bb содержит dark outer-transaction core, а aa2f55c добавляет wrapper-level writer/input containment. Live wrapper fail-closed блокирует coherent activation до полного direct-entry fence, receipt, reader-coherence и performance gates.

3.4. Comparator — датированный диагностический baseline, не второй реестр

Авторитетный изменчивый статус находится только в S3-NEXT-PARITY-REGISTER.md. Сохранённый там run 472de178-82bf-4c42-bc99-9276962fb421 остаётся каноническим, пока более новый результат не оформлен sanitized artifact-ом и не внесён в register.

Позднее runtime-наблюдение c8491e31-b10c-4121-a258-11d8ce1979c1 за окно 7–13 июля было получено после частичного kernel build и показало mismatch во всех девяти product-gates либо ложный aggregate green. Пока его artifact не зафиксирован в реестре, оно используется только как incident-evidence: запрещает cutover, но не доказывает девять независимых API-багов и не начинает G11.

3.5. Границы воспроизводимого evidence

Для любого evidence независимо от approval privileged inspection S3 выдаёт только bounded результат: timestamp, Git/spec/schedule digest, нормализованный grant envelope, step name/error code и идентификатор evidence; secrets, raw env, business rows и неограниченные live-логи в документацию не копируются.

Следующие действия не являются read-only и выполняются только в пределах утверждённой фазы после захвата штатных locks: session temporary-table create/drop, canon_next_compare (он пишет локальный audit и может отправлять alert), collector/ETL/catch-up и установка cron/systemd. Пароли не передаются в argv; операционные проверки используют защищённые wrapper-ы и root-owned secret files.

3.6. Новые находки обвязки и архитектуры

НаходкаРешение в этом плане
Documentation workflow запускал ! rg, но на GitHub runner rg отсутствовал, и exit 127 ошибочно превращался в successПерейти на portable grep, различать «нет совпадений» и scan error, закрепить тремя regression tests; generated catalogs публиковать только после --check
Инструмент G10 выполняется, но текущая active surface 67 245 LOC при цели 25 466, exact duplicates 12.36% при конечной цели <5%Не объявлять успешный запуск инструмента достижением целевой архитектуры; широкий frontend/Data API/kernel refactor остаётся заморожен до P5
Deadline/watchdog WIP для deploy содержал P0/P1 recovery/crash-window риски: outer signal bypass, helper без own PDEATHSIG, обратный lock order, раннее удаление state до MCP и cron backup без state/digestИсправлено локально в отдельном P3.7 candidate; не включать его в release до Linux contention/SIGKILL/MCP-retry proof. Releases до aa2f55c включительно этого WIP не содержат
CollectionRun.finish() считал raw_payload изменяемой таблицей в join FOR UPDATE; V3 collector намеренно имеет на ней только SELECT, INSERT, поэтому natural GoldApple 2724–2726 не sealed receipt при 29/29, а 2727 не sealed receipt после 28 successful subrequests и optional HTTP -1Не расширять grant как на S2. 0a36d6b блокирует только alias lineage; disposable MySQL 8 доказывает прежний 1142 и успешный настоящий seal. Не retro-seal старые process-local attempts; развернуть контролируемо, дождаться нового natural terminal success и лишь затем рассматривать receipt evidence
mcp-reindex-auto может отчитаться exit=3, пока remote next/spec-platform уже впереди checkout, а controlled deploy ещё не начал/не завершил swapЭто не доказательство потери индекса само по себе: 2026-07-16 после controlled deploy следующий timer закончил noop/0, а marker совпал с live SHA. Для P3.7 нужен отдельный выбор: sentinel обязан исключать такой tick либо expected checkout-ahead должен становиться явным skip, а не service failed.

3.6.1. Deploy/MCP incident на c17fe10 и точный recovery-контракт

Первый GitHub deploy c17fe10 (29450876221) fail-closed остановился не из-за app, Data API, collector или kernel-кода. Pre-deploy auto-reindex увидел новый GitHub SHA, пока live checkout ещё оставался на 392bd2c, завершился в phase=init без созданного candidate и оставил tombstone. Автоматический deploy retry пришёл примерно через 40,2 секунды, тогда как MCP safety contract требует 120 секунд settle, поэтому activation была правильно отклонена.

После полного settle выполнены exact-SHA recovery и отдельный --verify-activation для c17fe10; затем штатный deploy aa2f55c прошёл полностью. Collector и ETL в ходе incident/recovery не запускались. Причина и последствия тем самым локализованы в deploy/MCP orchestration, но сам race ещё не устранён. Обязательный follow-up:

  1. удалять tombstone без 120-секундного ожидания только для доказанного exact pre-Qdrant failure: phase=init, status running|failed, exact alias, отсутствуют source, snapshot и target-heads, а exact candidate отсутствует. Если tombstone уже существует, он обязан совпасть по candidate/alias и иметь пустой source; любой другой shape остаётся fail-closed;
  2. provision/attest оба fixed data-fence inode из deploy под уже унаследованным exclusive codebase FD до runtime activation;
  3. оставить workflow-level conditional wait длиннее 120 секунд только как защитный второй слой, если одновременно существуют deploy transaction и MCP tombstone; не заменять им точный state-machine fix.

3.6.2. Повторение race при 4c3afd3 и точный preventive fix

16 июля повторился тот же класс orchestration-инцидента. До controlled deploy таймер MCP успел записать новый job.json с phase=init, но checkout assertion остановила его до вычисления target heads, создания source/snapshot, Qdrant candidate или alias mutation. Первый post-commit MCP activator правильно создал durable tombstone для отсутствующего candidate; повторная попытка пришла через 40,8 секунды при 120-секундном settle-window. Activator вернул rc=3, поэтому outer wrapper правильно сохранил exact checkout и перевёл deploy в completion_unproven; app/API и root cron были quarantine, а collector/ETL не запускались.

Штатный same-SHA resume завершён 16 июля в 14:37 UTC без ручного удаления state или запуска runtime: COW reindex обработал 134 path, atomically переключил alias 13 619 → 14 430 points и записал marker 4c3afd3. Отдельный --verify-activation подтвердил activation receipt; затем проверены clean checkout, отсутствие sentinel/journal/failure marker, byte-exact root cron, active MCP units, healthy app/API и 200 на internal/public /new/login.

Кодовый candidate 197563a добавляет узкую immediate-reconciliation ветку в rag-tools/reindex_job.py. Она допустима только когда статус доказывает, что эта конкретная операция ещё не дошла до Qdrant: phase=init, status in {running, failed}, exact alias, отсутствуют source/snapshot/target heads и physical candidate. При существующем tombstone проверяется совпадение candidate/alias и source=null; несовпадение по-прежнему останавливает recovery. Regression tests фиксируют как немедленную безопасную очистку, так и отказ на несовпадающем tombstone. Это не является ослаблением общего 120-секундного протокола для всех missing candidate операций.

Порядок rollout обязателен: сначала штатный exact-SHA resume для уже committed 4c3afd3, затем --verify-activation, чистый sentinel/runtime/MCP/cron proof и только после этого deploy нового SHA с preventive fix. Запрещены ручное удаление state-файлов, ручной старт контейнеров или параллельный reindex; они не дают доказательства alias/receipt/cron согласованности.

3.6.3. Controlled rollout 0418c04 — deployed, но не подмена natural gates

Workflow 29507928342 завершился success 16 июля: полный CI прошёл до изменения S3, затем root wrapper развернул exact 0418c049eafc23b2e26805e32b7fa2b0877a6ce9. Независимая read-only аттестация после deploy подтвердила clean checkout, byte-exact root cron, отсутствие transaction/control-plane-failure/preimage markers, active mcp-gwptd.service и mcp-reindex-auto.timer, healthy app/API и 200 на Data API, internal /new/login и public /new/login.

Deploy MCP job 20260716T145134Z_327935_97cf7244450f4e90bdb7feeaaa019f93 завершился committed за 188,1 секунды: 7 paths reindexed, 0 pruned, alias атомарно перешёл с 14 430 на 14 432 points. Receipt, marker и target head точно закрепили 0418c04; отдельный --verify-activation также прошёл. Это доказывает rollout guard и исключает старый completion_unproven сценарий, но не является искусственным запуском collector, ETL, coherent publication или fault gate.

Следующее допустимое evidence для P1B-3 — только естественный build_all в 09:15 UTC следующего календарного цикла с развернутым manifest и pre-DML gate. До него P1B-3 не переводится в DONE; P1B-4/5/6 также сохраняют свои отдельные gates, а V3_KERNEL_COHERENT_PUBLICATION и Data API snapshot остаются default-off.

4. Что в прежнем подходе было сделано неправильно

  1. Одновременный stale целых групп трактовался как поломка десятков API, хотя причинный признак указывал на потерянные scheduler slots.
  2. ProductSpec-файлы S2 принимались за фактический runtime. На S2 исполняются legacy-классы, поэтому сравнивать нужно именно их с S3 ProductSpec/plugins.
  3. Модульность 79/79 ошибочно использовалась как доказательство parity. Она доказывает выбор runtime, но не идентичность запроса и данных.
  4. Проверялись общие status/count раньше, чем exact request fingerprint, raw lineage, stable keys и coherent latest revision.
  5. Ручные catch-up запускались как восстановление, но не был сначала создан механизм, который сам замечает и ровно один раз восполняет пропущенный слот.
  6. Deploy/MCP/backup assurance выросли раньше, чем был закрыт базовый путь schedule → request → intake → kernel → comparator.
  7. Интеграционные тесты не запускали ETL под точным gwptd_etl DB-контрактом, поэтому No database selected дошёл до штатного cron.
  8. До 3f1f152 build_all продолжал работу после ошибки. Теперь он fail-fast, но уже committed ранние шаги всё ещё могут оставить смешение поколений; атомарная публикация не доказана.

5. Что брать из S2, а что не переносить

Брать как oracle

Для каждого из 67 общих endpoint'ов:

  • account/campaign/business scope;
  • HTTP method, API version, path, query/body;
  • timezone, границы и длину окна;
  • cursor/offset/page limits и условия завершения;
  • async submit → poll → download;
  • timeout, retry, 420/429 и допустимые 404/zero-row semantics;
  • parser rules, raw evidence, skipped/partial policy;
  • destination, stable business key и replacement/dedup semantics;
  • порядок продолжения группы: один endpoint не отменяет остальные, но итоговый exit остаётся non-zero.

Уже доказанные различия для первой очереди:

  • ozon.realization: S2 — текущий плюс два предыдущих месяца; S3 — три закрытых месяца (monthsOffset=1);
  • ym.competitors_position: S2 обходит все категории; S3 прекращает после первого полезного отчёта, поэтому наблюдалось 240 против 60 строк.

Переиспользовать уже существующее на S3

  • scripts/runtime_codebase_lock.sh как общий shared codebase-immutability lock для runtime-процессов; exclusive сторону использует deploy/codebase writer;
  • scripts/runtime_db_attestation.sh вместе с db/connection.py::attest_connection() как основу identity contract, добавив отдельную ETL-only capability-проверку на том же соединении вместо нового параллельного attestation-контура;
  • monitoring/freshness_check.py и его first-run-grace как готовые тестовые сценарии bootstrap, но не как oracle наступления cron-слота;
  • monitoring/canon_next_compare.py и scripts/shadow_watch.py как существующие parity/self-watch контуры;
  • scripts/crontab.s3-next.txt как текущий versioned schedule до перехода на единый machine-readable registry.

daily_reconciliation.py, reconciliation.py и marketplace-specific reconciliation сверяют данные. Они не ведут durable slot ledger и не умеют обнаружить и ровно один раз восполнить пропущенный cron-slot.

Не переносить из S2

  • 66 endpoint-specific классов как новую архитектуру;
  • silent fallback ProductSpec → legacy;
  • fail-open DB lease;
  • freshness только для 23 endpoint'ов;
  • hardcoded credentials в wrapper;
  • дневной HTTP-cache, который может закэшировать transient/async status;
  • тяжёлый Amazon: full дважды в сутки, ежедневные BSR/Buybox и weekly backfill;
  • ограничение Lamoda status_dates первыми 200 страницами: S3 должен сохранять полный объём, а не воспроизводить известную потерю S2;
  • известные общие ошибки MAX(id), independent lifecycle MAX, YM revision inflation и legacy-формулы.

6. Зафиксированный scope

В scope

  1. 67 общих S2↔S3 endpoint-контрактов.
  2. 12 расширений S3 как отдельный extension scope; они не могут маскировать common parity.
  3. 25 job definitions, 75 scheduled ProductSpec и четыре exact unscheduled.
  4. Scoped kernel DB contract и атомарная публикация build_all.
  5. Девять data-gates: Orders, Stocks, Prices, Returns, Finance, Analytics, Storage, Turnover, Rating.
  6. Воспроизводимые sanitized evidence и обновление документации.

Вне scope до отдельного решения

  • любые изменения S2, его cron, credentials, DB или трафика;
  • Matrix UI/backend, новые product-features и широкая чистка Filament/Data API;
  • Qdrant upgrade и дальнейшее расширение backup/deploy assurance, кроме прямого blocker-а расписания;
  • redesign утверждённых формул;
  • schema-3 cutover, production promotion и выключение S2.

7. План исполнения

Оценки ниже — порядок величины, а не обещание срока. Следующая фаза не начинается, пока gate предыдущей не зелёный.

P0. Зафиксировать baseline и single-writer режим — быстро

  1. Создать checkpoint после утверждения этого плана.
  2. Зафиксировать SHA S2/S3, exact spec/pointer/schedule digests, последние natural runs, kernel build и comparator evidence.
  3. Остановить несвязанные code-потоки; один integrator пишет в next/spec-platform, остальные агенты только исследуют и тестируют свои зоны.

Gate P0: clean reproducible checkpoint; S2 read-only; ни одного неизвестного writer-а или незадокументированного runtime SHA.

P1. Исправить scoped kernel DB contract и coherent publication — 2–5 дней

P1A. DB contract — быстрый blocker

  1. Реализовать один явный default-schema contract одним из двух способов:
    • recommended: V3_MYSQL_DATABASE=gwptd_kernel в ETL wrapper и проводка значения через config.py в pymysql.connect(database=...);
    • либо полная квалификация всех temporary tables в пяти модулях, если default schema в handshake запрещена решением владельца.
  2. Одной совместимой волной обновить versioned migration, exact privilege allowlist в audit_etl_effective_privileges(), связанные deploy/control-plane contracts и regression tests. Разрешение — только CREATE TEMPORARY TABLES ON gwptd_kernel.*, не global privilege.
  3. Общий shell loader для monitor-ов оставить identity-only. В Python connection layer добавить отдельную ETL-only capability-функцию и вызвать её wrapper-ом до первого persistent/business DML. На одном exact connection она доказывает CURRENT_USER, server UUID, DATABASE(), нормализованный allowed/forbidden grant envelope и безопасный session temp-table create/drop с гарантированным cleanup.
  4. Прогнать exact-principal integration tests пяти подтверждённых модулей: stocks, storage, orders, returns и analytics. Root/SQLite/mock этот gate не закрывают.

Gate P1A — DONE: commits 9c625d1, ea7d5ff, 6394972, 5e71c7c и c43e2e7 развёрнуты. Live wrapper доказал exact principal/default DB/scoped grant, а ручной build завершил 15/15; прежние 1046, 1137, 1411 и 1267 не повторились. Natural scheduled proof относится к P5, не к P1A.

P1B-0. Fail-fast containment — DONE / DEPLOYED

3f1f152 прекращает build_all после первого failed step и запрещает пропуск SQL-ошибок invariant gate. Unit fault tests покрывают ранний, temporary-table, derived и финальный шаги; live ошибки storage, returns и analytics доказали, что последующие шаги не выполняются. Ранние уже committed шаги не откатываются, поэтому P1B coherent publication этим не закрыт.

P1B. Publication barrier — design завершён, implementation идёт

Доказанная поверхность

Source-инвентарь показал, что build_all меняет 14 уникальных kernel-таблиц: десять fact и четыре dimension/control. До P1B-1 один build содержал минимум 19 независимых commit-контекстов; resolve_identifiers сам делился на пять. Отдельные writers, которые тоже должны войти в fence:

  • build_ga_kernel --write каждые два часа меняет stocks и prices;
  • S20 attribute mirror меняет dim_product_attribute;
  • historic rating override меняет fact_rating;
  • standalone kernel modules и ручной WB stocks pipeline обходят build-level publication.

Read-only live inventory S3 на 2026-07-15 20:00:53 UTC:

  • MySQL 8.0.45, 22 InnoDB base tables, 3 view, 29 FK, triggers/events 0;
  • gwptd_kernel = 724,107,264 bytes; свободно на filesystem 99,635,093,504 bytes;
  • три физических slot заняли бы около 2.2 GB без запаса;
  • active InnoDB transactions, current row waits и wait edges в момент замера были 0; history list length 0;
  • крупнейшие таблицы: stocks ~1.42M rows / 313 MB, prices ~812K / 140 MB, analytics ~264K / 63 MB, storage ~201K / 55 MB.

Места достаточно и для outer transaction, и для трёх slot. Решающие неизвестные — не disk, а undo/redo growth, rollback time, input stability, writer serialization и reader consistency.

Выбранная последовательность
  1. Первый containment-механизм — один pinned InnoDB transaction для всех 15 шагов, hard invariants и activation receipt.
  2. Если exact-copy performance/fault gate покажет неприемлемые undo, locks или rollback time, fallback — три фиксированных generation-slot schema и атомарное переключение stable proxy views/pointer.
  3. Прямой group RENAME TABLE fact_* отклонён как первый вариант: он не охватывает dimensions, сложен с 29 FK, тремя view, metadata locks, grants и implicit DDL commit.
  4. Ветка a4644d2 не cherry-pick-ается: она записывает attestation поверх тех же 19 commit, допускает continuation после error, не блокирует incomplete inputs и имеет неполный input manifest. Из неё можно выборочно использовать lock/digest/test идеи только после повторного review.
P1B-1. Dark transaction core — DEPLOYED, NOT ACTIVATED

Commit a7e18bb:

  • добавил kernel_publication_transaction() с одним свежим pinned connection и единственным outer commit/rollback;
  • перевёл nested get_cursor() на savepoints без вложенных commit;
  • запретил reconnect, legacy cursor, permanent DDL, transaction control, stored procedures, multi-statements, executable comments и raw/private cursor access;
  • делает весь outer transaction rollback-only при любой SQL/cursor/ fetch/savepoint/cleanup ошибке, даже если caller её поймал;
  • заранее фиксирует курс USD/RUB до открытия transaction;
  • в coherent-режиме делает две ранее soft-caught фазы resolver fatal, не меняя default-mode до activation;
  • оставляет feature dark: штатный run_kernel_etl.sh fail-closed отклоняет любое truthy/unknown V3_KERNEL_COHERENT_PUBLICATION.

Live deploy proof: GitHub Actions 29448291307 завершён success; S3 checkout clean на exact SHA a7e18bb3ce6adba42e4c5a3164ccc9e3f2fd137c, app/API healthy, root cron не содержит opt-in, failure/control-plane markers отсутствуют, MCP same-SHA activation proven с 13 458 точками. Collector/ETL при этом не запускались и coherent mode не включался.

Доказательства checkpoint:

  • marketplace suite: 1052 passed, 30 skipped, 50 старых OpenPyXL deprecation warnings;
  • Data API suite: 144 passed;
  • dedicated unit/source guard: 113 tests green;
  • disposable MySQL 8: success commits all scopes; late/caught/temp-DDL faults не оставляют persistent rows; 4/4 green;
  • Ruff, git diff --check и architecture check green; active legacy files 0.
P1B-2. Fixed writer/input fences — DONE, DEPLOYED, LIVE PROVEN

Commit c17fe10 определил два fixed inode path и добавил единый fail-closed контракт их provision/attestation/acquire. Commit aa2f55c провёл этот контракт через официальные S3 launch-paths в порядке codebase → marketplace scope → input generation → kernel writer:

  • обычный live collector держит exact marketplace mutex и shared input fence;
  • run_yandex_daily.sh держит один Yandex mutex и shared input fence через обе дочерние стадии;
  • run_goldapple_snapshot.sh держит один Goldapple mutex через collector и projector, не делая запрещённый shared→exclusive upgrade;
  • run_wb_stocks_pipeline.sh держит WB mutex, exclusive input fence и kernel writer fence через все три ETL-стадии;
  • run_reference_sync.sh, run_s20_sync.sh, run_historic_rating_override.sh и run_kernel_etl.sh подключены к тому же canonical order с нужной shared/exclusive семантикой;
  • coherent publication повторно аттестует inherited input/kernel descriptors, когда production DB attestation активна;
  • exact selector parser принимает обе формы --mp value/--mp=value и --endpoint value/--endpoint=value, запрещает неоднозначные, повторные и пустые selector-ы до обращения к API/DB.

Checkpoint proof из clean GitHub checkout: marketplace suite 1093 passed, 25 skipped, Data API 144 passed, 1 warning. GitHub deploy 29451840780 и три сопутствующих workflow success. На live S3 оба fixed inode имеют exact owner/mode/type/link contract; app/API//new, cron и MCP same-SHA receipt зелёные. Для этого checkpoint collector/ETL вручную не запускались.

Commit ce06124 добавил fail-closed attestation в next_collector.py и во все 17 самостоятельных kernel/ETL main() до первого API/DB обращения. Direct Python process теперь не создаёт и не «чинит» lock inode, а обязан унаследовать полный exact-FD contract от штатного wrapper-а. Collector scope выводится из ProductSpec namespace; kernel сохраняет canonical order codebase SH → input SH/EX → kernel EX, включая отдельную historic-rating семантику. Clean detached checkout: marketplace suite 1118 passed, 30 skipped, Data API 144 passed; Ruff, py_compile, git diff --check и architecture gate зелёные. Collector/ETL не запускались.

GitHub deploy 29453907627 исторически не дошёл до изменения runtime: обе попытки были fail-closed отклонены в 22:02 UTC, после конца safe window. Это состояние заменено контролируемым workflow 29498311335: 16 июля в 12:29 UTC он проверил canonical SHA 361845a, test job завершился success, а deploy завершился success в 12:58 UTC.

Развёрнутый candidate добавил ещё два слоя P1B-2:

  • db6a18f переводит все scheduled monitor jobs с kernel-writer gwptd_etl@% на отдельный gwptd_monitor@%. Principal имеет только точные table-level SELECT и два comparator INSERT; kernel DML, schema-wide grants, temporary tables, roles, proxy, dynamic privileges и grant option запрещены exact audit-ом на deploy и при каждом connect/reconnect;
  • monitor читает только preprovisioned /etc/gwptd/secrets/monitor.env (root:root 0600) и отдельный /etc/gwptd/state/v3-monitor-db-attestation.env. ETL credential family удаляется из environment до Python, schema-3 child получает allowlist, а Telegram credentials явно экспортируются;
  • control-plane journal поднят до v4: он фиксирует absent либо exact monitor preimage без password/authentication string, удаляет только частично созданный deploy-owned account и принимает все bounded intermediate DCL состояния ETL privilege split. Существующему exact account пароль deploy не меняет;
  • 240b058 вызывает runtime_data_fence.py provision --wait 0 --codebase-fd 9 сразу после exact inherited FD8/FD9 verification и до MCP barrier, journal, schema, unit, cron или runtime mutation. Symlink, hardlink, path/inode swap и неверные owner/group/mode остаются fail-closed.

Deadline/watchdog WIP в эти коммиты не включён. Исторический review исходной черновой версии нашёл P0/P1 recovery окна; они исправлены локально в отдельном P3.7 candidate, но без Linux/S3 evidence остаются неразвёрнутыми. Поэтому ни один из этих P1B checkpoint не является доказательством P3.7 rollout.

P1B-2 закрыт следующими live доказательствами:

  1. S3 clean на exact 361845a; Docker app/API healthy, /new/login = 200, root cron byte-exact, journal/failure/transaction markers отсутствуют;
  2. gwptd_monitor@%, root-owned secret/state files и все три exact lock inode аттестованы на S3; MCP receipt закрепил 361845a и 13 619 points;
  3. direct next_collector.py --endpoint goldapple.snapshot завершился rc=3 с отсутствующим inherited codebase lock, direct kernel.etl.build_allrc=1 с тем же fence до API/DB; freshness cron естественно стартовал в 12:45 UTC во время deploy и выполнил freshness OK в 12:58 UTC после release lock.
Оставшиеся P1B gates — порядок работы
  1. P1B-2 rollout/deploy enforcement — DONE. Общий helper не переносится без разбора в _connect()/_cursor_cm(): ими пользуются также reference, monitor, preflight и historic paths с другой lock-семантикой.
  2. P1B-3 complete input manifest. Реализация развернута на 0418c04, локальная MySQL-проверка зелёная: lineage строится не из ComparisonSpec, а из всех 15 ETL steps; incomplete/partial input останавливает build до первой business DML. Последующее natural evidence выявило отдельный collector-side blocker: 2724–2726 записали 29/29 raw/typed/lineage rows; 2727 записал 29 rows, но имел 28 successful subrequests и optional HTTP -1, поэтому не может быть retroactively объявлен success. Во всех четырёх CollectionRun.finish() упал с MySQL 1142, потому что bare join FOR UPDATE пытался lock-нуть append-only raw_payload, на который у gwptd_collector сознательно нет UPDATE. 0a36d6b ограничивает lock alias-ом FOR UPDATE OF lineage; exact-grant disposable MySQL 8 proof зелёный, но code ещё не deployed. Синтетически закрывать старые receipts запрещено: retry/coverage/terminal timing существовали только в process memory. До natural terminal success после deploy статус DONE запрещён; ручной catch-up не заменяет штатный slot.
  3. P1B-4 same-transaction receipt. Dark implementation и journal v6 развернуты, а локальная MySQL-проверка зелёная: append-only activation с exact generation id, Git/step/input/formula/invariant digests входит в тот же COMMIT, что и facts; lost commit acknowledgement читает exact generation id. Journal attests full receipt surface, rejects foreign/non-empty drift и может восстановить owned partial DDL prefix после SIGKILL, не возвращая cron или runtime. До статуса DONE остаётся live lost-commit proof. Coherent mode до этого не включается.
  4. P1B-5 reader coherence. Реализация развернута, local disposable MySQL proof зелёный: SnapshotAPIRoute создаёт один lazy request-scoped REPEATABLE READ ... WITH CONSISTENT SNAPSHOT, и всё open/use/rollback/ close происходит в том же sync worker thread. Generation token сознательно не используется: P1B-4 receipt не покрывает самостоятельные GA/S20/WB writer-ы и дал бы ложную гарантию. Live mode остаётся off; до DONE остаются attest того, что все читаемые production tables InnoDB, reviewed mode rollout и live reader proof под writer contention.
  5. P1B-6 exact-copy performance/fault gate. Foundation уже фиксирует deployed proposed/test-only contract, exact 14-table fingerprint и strict evidence shape. До gate остаются owner-approved numeric budget, performance-equivalent MySQL clone, controlled 15-step faults на раннем/stocks/rating/invariant, duration/changed rows/undo/redo/history/lock/rollback metrics, три repetitions и signed evidence. Validator не может объявить activation eligible, пока эти элементы не доказаны.
  6. P1B-7 reviewed activation. Только после пунктов 1–5 отдельный commit снимает wrapper-block, включает режим и доказывает natural cycle. Если performance gate красный — не ослаблять transaction, а перейти к three-slot fallback.

Gate P1: P1A, P1B-0, dark P1B-1 и P1B-2 зелёные. Общий P1 остаётся открыт до P1B-3…P1B-7. До этого default runtime остаётся fail-fast, но не atomic; документация не должна выдавать dark код за activation.

P2. Построить machine-readable contract diff 67/67 — 1–2 дня

Стартовый артефакт P2 (2026-07-16): specs/contracts/s2-legacy-8dedd247a0c7-contracts.json — redacted static snapshot реального read-only S2 master@8dedd247; marketplace-collector-v3/scripts/audit_s2_s3_contract_matrix.py строит и проверяет docs/remediation/generated/S2-S3-ENDPOINT-CONTRACT-MATRIX.md. Он fail-closed проверяет exact set 67 common/12 extensions, source SHA, ProductSpec contract surface и отсутствие unknown mapping. Уже классифицированы три доказанных exact (lamoda.inventory, lamoda.promotions, lamoda.questions), пять fix_s3, включая lamoda.orders, lamoda.nomenclatures и lamoda.returns до S3-only canary, и один s2_known_bad_do_not_copy (lamoda.status_dates), а 58 строк намеренно имеют review_pending. Это рабочая основа P2, а не его закрытие.

P2 closure (2026-07-17, 76fbf0c): final common disposition содержит exact reviewed S2 endpoint-file SHA-256, current computed S3 contract SHA-256 и verdict по ровно 14 P2 surfaces. Изменение любого из двух contracts инвалидирует старый final verdict fail-closed. Current matrix audit доказывает 67 final/attested, 0 pending и p2_gate_closed=true; 12 S3 extensions остаются отделены. Строки с requires_s3_canary/known_s3_drift намеренно имеют disposition fix_s3 и переходят в P4, а не становятся exact без natural S3 evidence.

Сгенерировать матрицу S2 legacy class → S3 ProductSpec/plugin со столбцами:

endpoint_id, job, account/scope, method/path/version, query/body, window/timezone, pagination/caps, async polling, retry/backoff, cache, zero/partial policy, parser, raw destination, intake outputs, stable key, schedule, source evidence.

Каждая строка получает один статус:

  • exact;
  • fix_s3;
  • intentional_extension;
  • s2_known_bad_do_not_copy.

Unknown запрещён. Динамические secrets сравниваются по alias/scope, но значения не попадают в evidence.

Gate P2: 67/67 классифицированы и имеют current S2/S3 SHA-bound review attestation по всем 14 surfaces; missing/duplicate/unknown 0; два известных drift выше представлены failing contract tests; 12 S3 extensions отделены.

P3. Сделать расписание восстанавливаемым — 1–2 дня

Сейчас scripts/crontab.s3-next.txt содержит 25 executable job-строк: collector groups, ETL, monitor и reference sync. Durable slot-reconciler отсутствует, а существующие reconciliation-задачи сверяют данные, не доставку cron-слотов.

P3-A, deployed и static-proven (2026-07-16): schedules/s3-next.yaml стал единственным declarative source для 25 job-ов; compiler побайтно воспроизводит versioned crontab.s3-next.txt и fail-closed запрещает произвольный shell/runner, несовпадающий endpointSet, неверный completion contract и изменение canonical SHELL=/bin/bash / PATH. Static proof: 75 scheduled ProductSpec и четыре explicit unscheduled (amazon.buybox, amazon.sales_ranks, amazon.weekly_reports, wb.stocks). Workflow 29518336839 прошёл test+controlled deploy; S3/MCP exact на 8a336f3, а root cron digest остался byte-exact. Этот slice не меняет root-crontab, не запускает collectors/ETL и не заменяет durable ledger/reconciler ниже.

P3-B, deployed dark foundation (2026-07-16): шеститабличный activation/slot ledger фиксирует fresh generation, atomic claim/fence и bind source collection_run только в running до его seal. Pointer switch fail-closed, пока predecessor имеет pending/claimed slots. Schema получает exact SHOW CREATE attestation; scheduler principal, launcher, timer/reconciler, P3-specific cron mutation и ledger rows остаются выключены. 83c8a51 прошёл CI и controlled S3 deploy workflow 29528818504: exact DDL, пустые tables, отсутствие non-root direct grants/scheduler users, byte-exact root cron, healthy app/API и same-SHA MCP index 14 760 attested. Первый 4f3f29d deploy безопасно fail-closed откатил checkout/cron на missing normalizer argument; fix включён в 83c8a51. P3 scheduler/reconciler этим не активирован. Полный protocol: P3-SCHEDULE-SLOT-LEDGER-CONTRACT.md.

P3-C, deployed dark (2026-07-18): отдельный gwptd_scheduler@% имеет только USAGE, а credential gwptd_schedule_control@% остаётся root-only boundary для future Unix control service. Typed API принимает лишь activation/claim/heartbeat/bind/complete, derives owner из Linux peer UID и не принимает arbitrary SQL, owner, policy или artifact bytes от caller-а. Bounded journal v7 attests exact pair preimage/after-image, root-only secrets/state files и rollback only for its own absent→after-image transition. Read-only S3 proof на current runtime подтверждает exact limited grants, schedule-control.env root:root 0600, empty ledger и отсутствие journal/failure marker. Socket ownership, timer, cron mutation и launcher не созданы и остаются запрещёнными. Детали: P3-SCHEDULE-CONTROL-PLANE-CONTRACT.md.

Первый live preflight P3-C: workflow 29534017776 на 928fdf8 дошёл до Schema: P3-C schedule-control principals (dark), но остановился до account/secret mutation: P3-C ошибочно требовал 0700/0750 для shared /etc/gwptd/secrets, тогда как существующий OpenClaw/runtime contract требует root-owned 0755. Outer rollback вернул exact checkout и root cron. Исправленный candidate принимает 0755; credential остаётся root:root 0600.

  1. Создать machine-readable schedules/s3-next.yaml как единственный источник job list, cron, freshness expectations и reconciler; versioned cron становится генерируемым artifact-ом и сравнивается с exact ROOT-crontab digest.
  2. Создать durable UTC slot ledger: fresh generation_id, job_id, scheduled_at, spec/schedule/runtime digest, attempts, fencing/lease owner, result и type-specific completion proof; unique key — (generation_id, job_id, scheduled_at). expected endpoint set обязателен только для collector groups; ETL, monitor и reference sync имеют отдельные контракты завершения. Collector receipt принимает только pre-seal binding source run-а с exact request/spec digest, а не post-factum manual success.
  3. Первый rollout начинает watermark с момента deploy и не переигрывает всю историю. Первый due-slot вычисляется из schedule registry. First-run-grace freshness даёт сценарии bootstrap, но не является due-time oracle.
  4. Cron и persistent systemd reconciler должны вызывать один atomic slot claim, а не быть двумя независимыми launcher-ами. Rollout выполняется двухфазно.
  5. Reconciler после reboot/deploy запускает ровно один bounded catch-up через существующие locks/DB lease. Exit 75/8, активный lease или lock оставляет slot pending; duplicate launcher не создаётся. Возраст, attempts и API quota ограничены.
  6. GA slots coalesce; daily/weekly/monthly сохраняют разную семантику. Ручной или natural run закрывает slot без повторного API-вызова только при exact-set и completion proof.
  7. Full deploy имеет absolute deadline до следующего защищённого slot и обязан восстановить расписание либо rollback до deadline.
  8. Freshness monitor запускается независимо от launcher-а, отсутствие которого он должен обнаружить; ETL/monitor at-least-once семантика фиксируется отдельно.

P3.7. Absolute deploy deadline — historical bootstrap-receipt recovery completed, live fault proof открыт

После независимого review 2026-07-17 P0/P1 recovery окна были исправлены в candidate. На 2026-07-18 root seed и normal bootstrap подтверждены read-only evidence на S3, а compatible historical bootstrap receipt затем reconciled без замены installed guard files. Это завершает только historical receipt recovery; сама реализация не закрывает live-fault rollout gate:

  1. Root provision receipt /etc/gwptd/state/s3-next-deadline-bootstrap-dispatcher-provision.env фиксирует candidate_sha=8a4c9ad, dispatcher SHA bf62a106… и initial outer SHA 850c3f2…; оба совпадают с exact Git blobs.
  2. Normal bootstrap receipt /etc/gwptd/state/s3-next-deploy-deadline-bootstrap.env фиксирует new_sha=e3e04d, current outer SHA c8c93aac…, helper SHA 72e0106a… и exact service/timer SHA. Все пять installed файлов совпадают с receipt.
  3. gwptddeploy имеет NOPASSWD только на /usr/local/sbin/gwptd-next-deploy; direct sudo /usr/bin/python3 отвергнут. Effective deadline timer persistent/active без drop-ins; service использует exact root-owned helper, четыре canonical locks имеют root:gwptd 0660, transaction и bootstrap stage отсутствуют. Runtime и MCP healthy. Это не является доказательством аварийного recovery.

Локально реализованы следующие контракты:

  1. Runner никогда не передаёт root-коду Python или любой путь из $GITHUB_WORKSPACE. Workflow вызывает только уже разрешённый /usr/local/sbin/gwptd-next-deploy --check-deadline-bootstrap <SHA> либо /usr/local/sbin/gwptd-next-deploy --bootstrap-deadline-guard <SHA>. Outer wrapper проверяет root-owned dispatcher и запускает его через env -i с фиксированным interpreter/PATH. Dispatcher принимает только exact SHA, использует fixed GitHub origin next/spec-platform, fixed SSH transport, disables hooks/fsmonitor/replacement refs и читает source только как Git objects, а не из worktree. Каждая root-side Git операция получает это же изолированное окружение.
  2. Live wrapper до seed-а ещё не знает эти аргументы, поэтому первый запуск требует отдельного root-console seed в разрешённое окно. Root-only provisioner сначала берёт три canonical locks, затем заново доказывает exact remote SHA, candidate window и fast-forward от current live SHA. Он записывает durable seed stage до mutation, атомарно ставит dispatcher до outer wrapper, проверяет owner/mode/nlink/digest, пишет seed receipt и лишь затем удаляет stage. Он не изменяет live checkout, cron, БД, containers, units, MCP или collector schedule. Любой stage, missing/mismatched receipt или changed live SHA блокирует runner; только root может повторить exact same seed и завершить reconciliation. После появления canonical normal-bootstrap receipt initial seed receipt больше не блокирует следующие candidate deploy.
  3. /etc/gwptd/state/s3-next-deploy-transaction.env — единственный canonical blocker и deadline contract. Root-owned cron preimage остаётся отдельным 0600 backup до завершённого recovery, но его SHA-256 записывается в canonical state; после удаления backup state всё ещё способен доказать restored crontab. State создаётся до snapshot cron.
  4. Existing-transaction recovery делает rebind supervisor до любого fetch; новый fetch bounded (300s, TERM + 15s kill) и выполняется до создания transaction. Таким образом зависшая сеть не переживает durable deadline.
  5. Outer TERM/HUP/INT теперь передаётся inner supervisor и затем вызывает тот же outer finalizer: только он имеет право вернуть checkout, exact old-compose runtime и root cron. Python helper arm-ит собственный Linux PDEATHSIG после установки handler-ов, поэтому SIGKILL outer не оставляет его с FD6 без rollback child. Watchdog наблюдает FD6, а перед mutation берёт immutable lock-chain legacy → host → codebase → deadline; image_rollback_proven восстанавливается только после exact old runtime и отсутствия control-plane before-image. Unproven inner/control-plane phases остаются fail-closed.
  6. MCP/cron recovery идёт как durable handoff: state и backup не удаляются до точного восстановления MCP, bridge path/timer и cron. Временный MCP failure оставляет deadline_recovery_* phase, root cron quarantine и retryable systemd exit 75; только не доказанные состояния возвращают terminal 124. rollback_in_progress, inner_deploy, image_replacement_active и control-plane failures никогда не auto-resetятся watchdog-ом.
  7. complete_committed_deploy() проверяет каждый cleanup шаг явно. Effective systemd proof проверяет LoadState, FragmentPath, empty DropInPaths, enabled timer и active state вместо текстового systemctl cat.
  8. Перед каждой независимой target replacement bootstrap атомарно пишет root-owned durable stage: identity предшествующего receipt, exact live SHA, candidate SHA и digest всех четырёх B files (bfa9d1f). После SIGKILL retry разрешён только для того же B и только если каждый target равен verified A или verified B; C, unknown bytes и moved live checkout блокируются до mutation. Stage удаляется только после committed B receipt.
  9. Local evidence после security/recovery revision: focused P3.7/P3-C suite 120 passed, 14 skipped. Она включает runner/root boundary, fixed Git environment, fast-forward proof для initial bootstrap, повторную window/branch/live revalidation после locks, dangling deploy sentinel, incomplete seed stage, exact initial receipt и supersession initial receipt normal receipt-ом. Эти тесты не запускают collector, ETL, live S3 rollout или S2 write.
  10. Local real-process regression now kills the outer process with SIGKILL in a non-root Linux container, observes helper PDEATHSIG, verifies that every guard file is either attested A or B bytes, and proves the watchdog leaves the unproven state fail-closed. It passed 1/1 on Linux; the full local file is 72 passed, 1 skipped on Darwin. This is still not an S3 live-fault or controlled-deploy proof.
  11. A separate local two-process regression holds a temporary first canonical lock and proves recovery cannot begin until the actual flock call is released; after release it observes the order legacy -> host -> codebase -> deadline. It uses no DB, Docker, systemd or host path. This is only a local lock contract, not live S3 contention evidence.
  12. On 2026-07-18 a normal deployment at 61c3125 exposed a separate MCP completion race: while post-deploy reindexing was in progress, GitHub advanced next/spec-platform; strict equality correctly left the transaction in completion_unproven and quarantined MCP and root cron. Commit 7546178 passes the immutable deployment SHA to the reindex child. Only that child may accept a remote advance, and only when the advertised SHA is a verified descendant of the deployed SHA; it fetches that commit object without moving checkout or refs. Background indexing remains strict. Focused source tests passed 72; workflow 29651562797 then completed a controlled normal deploy at 772816a, with an exact clean checkout, healthy app/API, committed MCP index, active MCP units and all eight root schedule entries restored. This proves the normal handoff and its fail-closed recovery, but does not simulate the remote-advance branch on the live host.

Перед объявлением P3.7 live recovery proven остаются обязательными:

  1. Controlled normal full deploy через установленный wrapper уже green для exact 772816a (workflow 29651562797), но он не инжектировал remote advance во время reindex. Для этой новой ветки нужен отдельный документируемый controlled proof либо эквивалентное live evidence; один normal deploy не даёт права считать race-path доказанным.
  2. Отдельно выполнить документируемый contention/recovery proof: outer TERM, outer SIGKILL → helper PDEATHSIG, no-reset для unproven phase, MCP transient failure → retry и canonical lock contention. До него watchdog имеет только local proof, а P3-D launcher/reconciler запрещён.

Incident c17fe10 (exact cleanup only for the proven pre-candidate phase=init shape, inherited-FD data fences и workflow wait как второй слой) остаётся отдельным контрактом MCP deployment и не меняет семантику P3.7. Эта работа не закрывает P3, P3-C activation или P1B gates.

Gate P3: 25/25 разнотипных jobs имеют completion contract; collector scope — 75/75 scheduled specs и exact четыре unscheduled; тест «quarantine пересёк slot» даёт один catch-up, duplicate 0; активный lease или другой процесс не пересекается; installed ROOT-crontab и registry имеют один schedule digest.

P4. Исправить только доказанный endpoint drift — 1–4 дня

Порядок и уже доказанные ограничения:

  1. ozon.realization. S2 запрашивает текущий месяц и два предыдущих; S3 monthsOffset: 1 скрывает ожидаемый current-month 404 у posting и вместо этого собирает три прошлых месяца. Убрать offset можно только вместе с узким declarative exception: именно POST /v1/finance/realization/posting, именно 404, именно current calendar month = expected empty; historical 404, totals 404 и malformed 200 остаются fail-closed. Отдельно нужен per-subrequest stable-key DSL либо endpoint остаётся fix_s3: S2 хранит totals:YYYY-MM и <report_number>:<row_num>, а S3 сейчас даёт None.
  2. ym.competitors_position. S3 прекращает обход после первого успешного XLSX, тогда как S2 проходит все eligible categories. Простое удаление break запрещено: ранее неограниченный S3 run был остановлен через 24 минуты как quota-burning. Сначала нужен P3-controlled bounded quota/coverage contract: discovered/attempted/succeeded/failed categories, одинаковый retry для 420 и 429, fixture c несколькими категориями и run-scoped evidence. Data API должен вернуть legacy default your_share_pct DESC с детерминированным tie-breaker, а не global latest snapshot по date/category id.
  3. Остальные fix_s3 из P2 — по одному endpoint'у, только после того как доказательство scheduler slot и quota budget определены.

Статус ym.competitors_position, локальный кандидат 2026-07-18: реализован P4 receipt для runtime-discovered категорий: exact discovered/attempted/succeeded/failed, maxSegments=12, fail-closed cap и единый bounded retry для 420 и 429. Fixture покрывает несколько категорий, исчерпанную quota и cap; сканер документации сохраняет generate/poll API в usage catalog. Локальная проверка: 1612 passed, 58 skipped. Это не закрывает P4: кандидат должен быть ребейзен после platform/WB PR, затем пройти ровно один последовательный S3-only canary и следующий штатный YM-цикл.

Для каждого: sanitized fixture replay → contract test → S3-only canary в разрешённое quota-window → stable-key/raw/intake comparison. S2 не запускается и не изменяется; используются его source contract и уже имеющиеся read-only данные.

Gate P4 для endpoint: exact request fingerprint; page/report count объяснён; parsed/skipped соответствует контракту; partial/failed=0; common stable keys и контрольные поля exact либо расхождение вынесено на owner review.

P5. Один естественный полный цикл — минимум сутки

Дождаться цепочки без ручного catch-up:

scheduled slot → collector → intake lineage → build_all 15/15 → comparator.

Ручной run может диагностировать код, но не закрывает natural-cycle gate.

Gate P5: все наступившие slots закрыты; freshness 75/75; runtime commit, spec digest и schedule digest exact; kernel generation coherent; comparator не incomparable.

P6. Закрыть row-level parity — от 3 дней

Строгий порядок зависимостей:

  1. Primary: Orders → Stocks → Prices → Returns.
  2. Financial: Finance → Analytics → Storage.
  3. Derived: Turnover → Rating — только после зелёных входов.
GateОбязательное доказательство
Ordersexact stable key, qty/price/revenue/status, duplicate 0, complete lineage
Stockscommon-scope exact, snapshot/retraction lineage, duplicate 0; mp10/history отдельно
Pricesпять price fields exact на common scope; GA/1C extensions отдельно
Returnskey/qty/amount/reason/status exact, NULL-baseline сохранён, natural post-fix cycle
Financeшесть monetary fields exact, operation/item coverage complete
Analyticsшесть metrics exact после latest-revision dedup
Storagecoherent multiset sum, WB+Ozon+YM coverage, shuffle invariant; никакого false green MAX(id)
TurnoverComparisonSpec v2, grain/lineage/formula digest, common window exact
RatingComparisonSpec v2, row/formula/CBR-rate/MetricSpec lineage; approved semantics only

Stocks, Storage, Turnover и Rating переводятся с ComparisonSpec v1 на строгий v2. Tolerance не ослабляется. incomparable, missing lineage и необъяснимые canon-only/ next-only строки блокируют gate.

Gate P6: каждый набор имеет только green или отдельно утверждённый владельцем accepted_difference. Сейчас accepted-difference ledger пуст и остаётся пустым до предъявления технических доказательств.

P7. Burn-in и только затем предложение cutover — 3 окна + 14 дней

  1. Три последовательных сопоставимых закрытых окна — early stability gate.
  2. Затем 14 последовательных natural G11 days без ручной подмены слотов.
  3. Weekly job должен естественно пройти внутри streak.
  4. Monthly Amazon требует отдельного естественного due-slot proof; 14 дней не превращают ещё не наступивший monthly slot в зелёный.
  5. Любое изменение formula/spec/schedule digest, partial build или unexplained parity сбрасывает streak.

Cutover остаётся отдельным решением владельца по WAVE-7-S2-CUTOVER-RUNBOOK.md.

8. Риски, rollback и stop conditions

8.1. Риски и митигации

ФазаРискОбязательная митигация
P1 DBglobal/лишний grant либо несовместимость code↔grant↔deploy auditодна совместимая волна; только gwptd_kernel.*; exact envelope test
P1 DBформальный env не выбирает schemaпроводка config→PyMySQL и exact DATABASE() test либо полная квалификация
P1 publishstaging/swap блокирует readers, ломает FK/view или заполняет дискdesign inventory, exact MySQL concurrency/fault tests, lock-timeout и retention
P3cron и systemd дважды запускают slot либо switch strand-ит старый retryодин atomic claim, unique (generation_id, job_id, scheduled_at), fencing token и CAS+drain predecessor generation
P3ещё не наступивший slot принят за пропущенныйUTC schedule registry + deploy watermark; freshness grace не используется как due oracle
P3/P4catch-up конкурирует с S2 за quotabounded age/attempts, quota-window и stop при пересечении
P6повтор false green (MAX(id), incoherent revisions)ComparisonSpec v2, multiset/lineage/shuffle-invariant
Всеdirty checkout или чужой writershared/exclusive runtime_codebase_lock.sh, clean checkpoint и digest attestation

8.2. Rollback по фазам

  • P0: runtime не меняется; неутверждённый evidence не продвигает gate.
  • P1 DB: ea7d5ff сохраняет exact grant preimage, проверяет afterimage и считает своим только scoped delta CREATE TEMPORARY TABLES ON gwptd_kernel.*. Rollback отзывает его лишь при отсутствии иного drift и после доказанного отсутствия активного ETL; слепой global REVOKE запрещён.
  • P1 publication: failed generation никогда не становится active. Для уже активированного поколения выбранный P1-механизм обязан иметь протестированный возврат на сохранённое предыдущее поколение; collector pointer этим механизмом не считается.
  • P3: остановить/disable reconciler и timer, доказать отсутствие claim/lease, восстановить exact ROOT-crontab preimage/digest. Ledger сохранить read-only для аудита; удаление возможно только отдельным owner decision.
  • P4: вернуть проверенный runtime/spec bundle и exact полный pointer-set через поддержанный deploy/control-plane rollback либо временно снять job из schedule по утверждённому контракту. Одиночный pointer flip запрещён: S3 fail-closed и legacy fallback отсутствует.
  • P6: comparator/evidence не меняют runtime; ошибочный artifact помечается invalid и не используется в gate. S2 остаётся неизменным oracle.

8.3. Stop conditions

Работа останавливается и не переходит к следующей фазе, если:

  • обнаружена любая запись на S2;
  • активны чужой collector lease/process, deploy sentinel или несовместимый lock;
  • checkout dirty либо runtime/spec/schedule digest не совпадает с ожидаемым SHA;
  • наступивший in-scope slot пропущен или выполнен дважды;
  • новый наступивший in-scope run имеет partial, failed или необъяснимый skipped; намеренно unscheduled и их исторические состояния оцениваются отдельно;
  • build_all не 15/15 или изменил active generation до полного gate;
  • comparator incomparable или не имеет row-level lineage;
  • предлагается ослабить tolerance либо принять difference без решения владельца;
  • S2 и S3 могут одновременно потратить одну ограниченную API quota.

9. Разделение агентских сессий при исполнении

ПотокРазрешеноЗапрещено
Integratorединственный writer, commits/push, итоговые gatesпараллельное редактирование другими сессиями
S2 Contract Oracleread-only source/cron/log/DB evidenceзапуск, deploy, cron/DB/secrets changes
S3 KernelP1, exact-principal tests, publish barrierAPI drift и S2 writes
Contract + SchedulerP2–P3, fixtures, ledger/reconciler testsbusiness formulas
ParityP4–P6, ComparisonSpec/evidenceaccepted differences и cutover
Docs/Evidenceregistry, sanitized artifacts, handoffruntime mutation

Каждый поток отдаёт integrator-у: base SHA, changed paths, tests, live actions, rollback, unresolved blockers. Integrator не принимает незакоммиченный «мешок» из нескольких доменов.

10. Зафиксированные решения владельца

Владелец разрешил исполнение всего плана, commits, push и изменения S3. Поэтому нижеприведённые пункты считаются утверждёнными до отдельного изменения решения:

  1. Matrix/Qdrant/широкий refactor заморожены до P5.
  2. P1 kernel DB contract выполняется раньше дальнейших ручных collector-runs.
  3. Common-first обязателен: 67 S2 endpoint'ов проверяются отдельно от 12 расширений S3.
  4. Известные ошибки и ограничения S2 не копируются ради наивного count parity.
  5. Расписание восстанавливается через durable slot ledger и один reconciler, а не надежду на cron.
  6. Rating/Turnover не проверяются раньше исходных data-gates.
  7. До предложения cutover нужны три зелёных окна и затем 14 natural days.
  8. Для gwptd_etl разрешён только schema-scoped CREATE TEMPORARY TABLES, а ETL-only capability preflight сохраняет строгий deploy privilege audit.
  9. Publication mechanism выбирается через P1 design gate; RENAME TABLE не считается готовым решением без FK/view/concurrency proof.

Отдельный SELECT-only principal/observer на S2 может понадобиться для непрерывной attestation, но это изменение S2. Оно не входит в этот план без отдельного явного разрешения.

11. Definition of Done программы

S3 можно назвать «делает то, что S2, но лучше» только когда одновременно:

  • 67/67 common endpoint contracts доказаны;
  • 12 extensions отделены и не искажают common parity;
  • 25/25 jobs, 75 scheduled и четыре unscheduled совпадают с registry;
  • потерянный slot автоматически и ровно один раз восстанавливается;
  • exact-principal ETL-only preflight доказывает identity, DATABASE(), scoped temp privilege и безопасный session temp create/drop;
  • kernel build публикует одно coherent generation только после 15/15 и hard invariants; fault tests сохраняют предыдущую active generation;
  • девять data-gates зелёные либо имеют точечное owner-approved отличие;
  • три закрытых окна и 14 natural days пройдены;
  • S2 всё это время остаётся неизменённым production-каноном и rollback oracle;
  • документация и MCP index соответствуют одному repository SHA, а каждый runtime-evidence явно фиксирует свой deployed SHA и не выдаёт docs-only SHA за runtime revision.