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@5f2a3a1Historical functional baseline 2026-07-20 -- S3 code
47f1a66: guarded activation advanced the S3 staging runtime fromd51d474to47f1a664c2a5dae29572d57c5934a9d7e795e687. At the time of this evidence the checkout was clean and matchedorigin/next/spec-platform; bothgwptd-app-newandgwptd-data-apiwere healthy, and the MCP index committed the same SHA at exactly16,466points. This functional release contains two narrowly tested code fixes: interface-variant entry routing and support for probes ofruntime_discoveredscopes. A later documentation-only descendant may change the checkout SHA without changing this code scope; always obtain the exact live SHA throughmcp__gwptd__repo_statusbefore collecting new evidence. A real no-write S3 probe ofym.competitors_positionnow completes with HTTP200; its receipt explicitly reportsfalsefor 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 throughhttps://mp.hyp.ru/new*; within the S3 application container,interface_variant=newdirects/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_allcycle on an unchanged exact runtime SHA. S2 was not touched. This supersedes thed51d474status block below only as the current runtime statement; its dated evidence remains intact. Details: Live Evidence Update 2026-07-20 S3 Activation of47f1a66.Historical status supersession 2026-07-19 — S3 тогда был
d51d474530051d0e7e69d6246dda934d2e8410d8, clean / in sync: guarded activation ofd51d474verified. Read-only attestation: the S3 checkout is clean and in sync at this exact SHA,gwptd-app-newandgwptd-data-apihealthy, and the MCP index atomically committed the same SHA at exactly16,456points. The deployed range excluded Basket A2. No P1B, P3, P4 or P5 gate changed state: P1B remains not proven and P1B-3 staysNATURAL REFERENCE + BUILD EVIDENCE PENDING; P3-A/B/C stayDEPLOYED / DARK / NOT ACTIVATED; both P4 endpoints stayfix_s3; P5 staysGATES NOT STARTED. This deploy changed the runtime SHA and therefore invalidated the prior quiet-window natural-cycle proof that was accumulating on the earlier3dff005runtime: the next admissible P1B-3 evidence must be a fresh, untouched natural04:30–09:15 UTCcycle on the unchangedd51d474. This supersedes the dated3dff005/6dff3abruntime 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 ofd51d474.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 run2924вернулdegraded, а неok. Контейнерыgwptd-app-newиgwptd-data-apihealthy; collector runtime работает из root crontab, а не из одноимённых systemd service.Operational closure 2026-07-17 20:52 UTC — S3 сейчас
bbc9c35240af6089b182c4320eef67a466dfb349: первый guarded deploy862af84fail-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 snapshot99 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 runym.servicesrun_id=2858:success,1341/1341,429=0, все1341raw canonical and lineage receipts sealed; historical transient catch-up failed-state сброшен без полного ручного--mp ymcatch-up.Live correction 2026-07-17 19:39 UTC — S3 сейчас
e3e04dff4ca1c06f71ec52ea40dd2ca4b41a73c9: guarded deploy завершился successfully после root deadline bootstrap; transaction marker отсутствует,gwptd-app-new/gwptd-data-apihealthy,/new/loginи Data API health вернули200, а MCP index atomically указывает на exact deployed SHA.gwptd-deploy-restore-deadline.timeractive; 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. MCPstate/index-receipt.jsonзакрепляет тот же SHA,14 840points (2026-07-16T20:44:06Z). GitHuborigin/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: S35a8110e→7553449(PR#40) в06:26:59 UTC, затем7553449→db3a907(P4-мерджи821bee6ym +7ac6568ozon). Дельта5a8110e→db3a907: 0 новых SQL-миграций,data_api//app/не менялись (контейнеры не пересобирались), root crontab коллектора не менялся. Постдеплой: контейнеры healthy (gwptd-app-new,gwptd-data-api— Up, healthy),/new/login200, data-api/health200. Off-window патч НЕ в проде —origin/nextforce-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 SHA8a336f33dd7cfe8a1882c4e9f5b874e0fdaf2114после workflow29518336839. 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 обработал20paths и atomically сменил active index14 532 → 14 574points. Ни collector, ни ETL вручную не запускались, S2 не изменялся. Последний ручной exact-principalbuild_allзавершён 2026-07-15 19:42:49 UTC на kernel-кодеc43e2e7:15/15, hard invariant gate passed.Последний deployed implementation checkpoint:
361845a— P1B-2 full enforcement. Workflow29498311335(test + deploy) success; app/API и/newhealthy, 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 guard197563a. Workflow29507928342прошёл полный 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 обработал7paths, atomically сменил alias14 430 → 14 432points и закончилcommitted. Миграции P1B-3/4 установлены; P1B-4 publication остаётся dark,V3_KERNEL_COHERENT_PUBLICATIONпо-прежнему fail-closed запрещён wrapper-ом, а liveDATA_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-ов. Workflow29518336839прошёл test+deploy; 75 ProductSpec остаются scheduled, четыре endpoint осознанно unscheduled, а digest generated cron совпадает с установленным расписанием. P3 ledger/reconciler и P3.7 watchdog этим не реализованы.Последний P3-B dark deployment checkpoint:
83c8a51(83c8a510…) — workflow29528818504success 2026-07-16 19:58 UTC. CI (including a disposable MySQL 8 SHOW CREATE job) и controlled S3 deploy прошли; postcheck подтвердил clean same-SHA checkout/MCP index14 760, microsecondcollection_runtimestamps, шесть пустых ledger tables,0non-root direct grants и scheduler users, byte-exact root cron, healthy/newи Data API. Первый4f3f29ddeploy 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-ом и не конфликтуют с естественным циклом.
Текущий журнал исполнения
| Фаза | Статус | Проверенное состояние |
|---|---|---|
| P0 | DONE | Single-writer действует; GitHub, clean S3, generated docs и MCP были сведены на 9310ae5; дальше каждый checkpoint снова доказывается отдельно |
| P1A | DONE / DEPLOYED | Exact DB contract и scoped grant live; пять temporary-table модулей прошли под gwptd_etl; ручной build_all завершён 15/15, без 1046/1044/1142 |
| P1B-0 | DONE / DEPLOYED | 3f1f152 останавливает build на первом failed step; live-сбои storage, returns и analytics доказали, что последующие шаги не запускаются |
| P1B-1 | DEPLOYED / DARK | a7e18bb: 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-2 | DONE / DEPLOYED / LIVE PROVEN | 361845a развернут 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-3 | DEPLOYED / 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-4 | DEPLOYED / DARK / NOT LIVE PROVEN | Attempt/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-5 | DEPLOYED / DEFAULT-OFF / METADATA ATTESTED / NOT LIVE PROVEN | SnapshotAPIRoute развернут, 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-6 | DEPLOYED FOUNDATION / TEST-ONLY / NOT A GATE | Proposed/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. |
| P1B | IMPLEMENTATION IN PROGRESS / NOT ACTIVATED | P1B-2 действует live; complete manifest, same-transaction activation receipt, lost-commit reconciliation, reader coherence и performance/fault gates остаются отдельными следующими gates |
| P2 | DONE / STATIC CONTRACT ATTESTATION PROVEN | 76fbf0c довёл 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.7 | HISTORICAL BOOTSTRAP-RECEIPT RECOVERY COMPLETE / LIVE FAULT PROOF PENDING | Root 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 MUTATION | 8a336f3, 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 ACTIVATED | 83c8a51, 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 ACTIVATED | Read-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 ACTIVATED | Declarative 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 открыт. |
| P4 | DEPLOYED 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 1→0 + узкий 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–P7 | GATES NOT STARTED | Natural 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стартовал на S38932aa7после того, как все31/31active ProductSpec inputs стали terminalsuccessс sealed receipt на том же runtime. Он корректно остановился до business DML с единственной причиной:reference:onec_nomenclature_ref:reference_attempt_running. - Read-only evidence: свежий 1С reference attempt
16cb5fd6-5a92-414b-9082-3201c0db8b7bимеет только eventstarted(04:30:01 UTC); ниsuccess, ниfailedevent не записан.gwptd_referenceнамеренно имеет толькоSELECT, INSERTна append-onlyreference_snapshot_attempt_event, но producer делалSELECT ... FOR UPDATE, для которого MySQL требуетUPDATE. Ошибка ломала и publish, и попытку записать terminal failure, поэтому состояние оставалось fail-closedrunning. - Candidate
6c1452cзаменяет этот locking read на обычныйSELECT. Primary key(attempt_uuid, terminal_slot)по-прежнему запрещает два terminal events; grants не расширяются. Локально: reference/build-input tests55 passed, trust-boundary/manifest tests10 passed, 5 skipped. Subsequent deployment включил этот fix в current S3ea11a23; terminal event не подделывался и ручнойbuild_allне запускался. Исторический 04:30/09:15 result остаётся pre-fix evidence, а следующее допустимое acceptance evidence — новый natural reference, затем новый naturalbuild_allcycle.
Live Evidence Update: 2026-07-19 Mixed-Runtime Rejection
- Natural reference at
04:30 UTCnow succeeded: attempt3b611a9d-8140-40b6-9e36-f9c49772fb60hasstartedandsuccessevents on runtimeaa769c50bbd160a36c1426ede9e651501a874682. Its sealed receipts areonec.nomenclature=19,549andonec.warehouses=119; the scheduled 1C, WB, Ozon, YM and Lamoda collector runs for the same day also usedaa769. - The
09:15 UTCkernel wrapper instead sawcfea7f513cd23fda0d1dc461eaefa34102ce94d1and stopped before business steps withkernel 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
journalctland Git reflog show the cause: root explicitly rangwptd-next-deploy --owner-authorized-off-window --expected-shaat08:01,08:26,09:03,09:34and09:40 UTC, including thecfeacheckout. The normal wrapper already prevents this path:ops/bin/gwptd-next-deploypermits full deploy only at12:30-22:00 UTC(Sunday after14: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 next04:30-09:15 UTCnatural cycle; then run the read-only P1B-3 verifier. - The bounded S3 access polygon is independently green:
wb.balanceplan mode followed by one--executerequest returned HTTP200, extracted one item and wrote no cache,collection_run, intake or ETL data. Local targeted verification is185 passed, 5 skippedfor P1B-3/deploy/probe contracts and17 passed, 1 skippedfor Weekly KPI/Data API contracts.
Live Evidence Update: 2026-07-19 Weekly KPI Contract Deploy
- The production PageSpec route
/new/test?page_code=weekly.kpihad a real UI contract mismatch: its grid exposed100rows whilereports/weekly-kpiintentionally accepts at most50, and its sole KPI asked for nonexistenttotals.records. Commit7b1e7b2aligns the active GridSpec with the required[10, 25, 50]selector/default10, restores the five requested display columns, and binds KPI tiles toweeks,models,qtyandrevenue. It adds API boundary and PageSpec contract tests; it changes no collector, cron, schema, ETL or S2 resource. - GitHub Actions run
29693999431did 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 permitted12:30-22:00 UTCwindow the root-owned guarded wrapper was then invoked with exact--expected-sha2b1bcfc5819659ecd98d17aeaae5552891bd03c8. - The guarded S3 transaction committed
ccecdb993b2f8355677e5bf37d5a13eb8221c2de -> 2b1bcfc5819659ecd98d17aeaae5552891bd03c8.gwptd-app-newandgwptd-data-apiare healthy; Data API/healthreturns{"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,228points). No S2 write, manual collector, receipt rewrite or manual ETL occurred. - A separate bounded S3 polygon for
ym.promosis green on the same runtime: exactly one POST returned HTTP200, extracted5items, sampled/mapped3, and reportedcache=false,collection_run=false,intake=false,etl=false. Keep2b1bcfcunchanged through the next natural04:30-09:15 UTCcycle 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 baseline2b1bcfcincludes 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 committedCLAUDE.mdstructural 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.shexited0(backend and UI catalogs current, documentation registry valid with502Markdown files, remediation history valid63/63, business canon integrity valid); the maintained PHP documentation suite reported12 passed, 1544 assertions; the focused Python collector suite reported16 passed. - GitHub Actions run
29697173143did 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 permitted12:30-22:00 UTCwindow the documented guarded manual S3 deploy was then invoked on S3 only with exact--expected-sha3dff005c373d758d22d9b754ac7ef8baf980ad9e; both the deploy transaction and the activation verifier returnedrc=0. - Post-deploy attestation on the new runtime: the S3 checkout under
/opt/gwptd-analytics/repois clean on the same SHA; no transaction sentinel, stage marker or failure env remains. Publichttps://next.mp.hyp.ru/new/loginreturned200;/new/testreturned302(auth redirect, as expected for an anonymous request); an internal Data API report endpoint returned200from inside the S3 network.gwptd-app-newandgwptd-data-apistayed healthy throughout. - S2 was not touched. No collector, ETL, receipt rewrite, manual reference
attempt, manual
build_all, schema migration, DB credential change orGWPTD_API_TOKENSrotation was performed. - This is not a P1B-3 natural-cycle proof. No new terminal reference slot
and no natural
09:15 UTCbuild_allcycle 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 naturalbuild_allon the unchanged SHA3dff005.
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-newandgwptd-data-apihealthy, and the MCP index atomically committed the same SHA at exactly16,456points. - The deployed range from the prior
3dff005runtime 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 orGWPTD_API_TOKENSchange, 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 remainDEPLOYED / DARK / NOT ACTIVATED(including the newly present reconciler code); both P4 endpoints remainfix_s3; P5 remainsGATES NOT STARTED. - S2 was not touched. No collector, ETL, receipt rewrite, manual reference
attempt, manual
build_all, schema migration, DB credential change orGWPTD_API_TOKENSrotation 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
3dff005runtime: no new terminal reference slot and no natural09:15 UTCbuild_allcycle has yet run on the unchangedd51d474. The historical3dff005and6dff3abentries 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 naturalbuild_allon the unchanged SHAd51d474.
Live Evidence Update: 2026-07-20 S3 Activation of 47f1a66
- The S3 staging runtime advanced from
d51d474to exact SHA47f1a664c2a5dae29572d57c5934a9d7e795e687through the normal guarded deployment wrapper. Read-only post-activation attestation found the checkout clean and in sync withorigin/next/spec-platform,gwptd-app-newandgwptd-data-apihealthy, and the MCP index committed at the identical SHA with16,466points. - The release scope is deliberately small: variant-aware root and auto-login
entry routing, a probe fix for collectors with
runtime_discoveredscopes, and documentation. Local verification before activation:18endpoint-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 manualbuild_allwas performed. - A live S3 no-write probe of
ym.competitors_positionexecuted its initial runtime-discovery request successfully with HTTP200. Its receipt declaredfalsefor cache,collection_run, intake and ETL writes. This proves that the former pre-networkconfigRefprobe 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/newand/new/weekly-kpi-apireturn the expected SSO redirect, while/new/loginreturns200. The public host root/remains the S2 legacy entrypoint and redirects to/admin; direct routing inside the S3 new-application container correctly sends/to/newwheninterface_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 remainfix_s3; and P5 remainsGATES NOT STARTED. Since the activation changed the runtime SHA, the next admissible P1B-3 evidence is one fresh, untouched natural terminal reference followed by naturalbuild_allon unchanged47f1a66. S2 was not touched.
1. Утверждённое решение владельца
Владелец утвердил последовательность ниже и назначил эту сессию единственным integrator-ом. Работа идёт по gate-ам; незакрытая фаза не подменяется ручным catch-up или общим зелёным status/count.
Утверждённая последовательность:
- заморозить несвязанные рефакторинги, Matrix, Qdrant и расширение платформы;
- первым исправить доказанный разрыв DB-контракта kernel;
- затем автоматически сравнить 67 общих endpoint'ов S2 и S3 на уровне запроса, окна, пагинации, parser-а и business key;
- отдельно устранить потерю cron-слотов;
- исправлять только доказанные endpoint-drift по одному;
- закрыть первичные, финансовые и только потом производные data-gates;
- считать готовность только по естественным циклам, а не по ручному 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 не работает» объединяет три разных проблемы:
- Доставка запусков. Долгий deploy временно снял root cron, а восстановление MCP/Qdrant затянуло quarantine. Cron не имеет durable ledger и не переигрывает уже прошедшие слоты. Поэтому одновременно протухли целые группы, хотя их API не ломались.
- Kernel после сбора. Исторический
MySQL 1046: No database selectedустранён вместе со следующими MySQL-дефектами storage, returns и analytics. Ручной exact-principalbuild_allнаc43e2e7прошёл15/15. Dark outer-transaction core атомарной публикации реализован и развёрнут, но не активирован и не доказан end-to-end: P1A закрыт, P1B остаётся отдельным обязательным gate-ом. - Незакрытый паритет. 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 |
| Исполняемый runtime | legacy-классы 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:00 | 1С | 1/1 success, 2:04 |
| 09:00 | WB | 22/22 success, 48:26 |
| 09:25 | Ozon | 18/18 success, 40:17 |
| 09:50 | Yandex Market | 18/18 success, 75:17 |
| 12:00 | Lamoda | 7/7 success, 57:55 |
| 13:10 | kernel build_all | 14/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 deploy | GitHub Actions 29451840780: test и deploy success; transaction/failure markers отсутствовали; docs 29451843635, architecture 29451840809 и refresh 29451840783 также success |
| Current MCP receipt | target 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 P1A | exact-principal capability preflight green; ручной build_all 15/15; все hard invariants green |
| ProductSpec/pointers | 79/79, exact, fail-closed |
| Расписание | 75 endpoint'ов scheduled; четыре исключены точно: amazon.buybox, amazon.sales_ranks, amazon.weekly_reports, wb.stocks |
| Последние наступившие слоты | 74 endpoint'а имеют последний success; amazon.monthly_reports ещё не наступал |
| Lease/lock | DB 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.
Первичный дефект был двухзвенным:
- wrapper не выбирал default schema и connection layer не передавал её в PyMySQL;
- versioned grant-контракт
gwptd_etlне содержал schema-scopedCREATE TEMPORARY TABLES.
Исполнение и доказательства:
3f1f152сделалbuild_allfail-fast и SQL-ошибки invariant gate fatal;9c625d1провёл ETL-onlyV3_MYSQL_DATABASE=gwptd_kernelдоpymysql.connect(database=...)и добавил exact identity/schema/role/grant/temp capability preflight;ea7d5ffдобавил grant preimage/afterimage в deploy journal и единственный owned deltaCREATE TEMPORARY TABLES ON gwptd_kernel.*с ограниченным rollback;6394972устранил MySQL1137в 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:
- удалять tombstone без 120-секундного ожидания только для доказанного exact
pre-Qdrant failure:
phase=init, statusrunning|failed, exact alias, отсутствуют source, snapshot и target-heads, а exact candidate отсутствует. Если tombstone уже существует, он обязан совпасть по candidate/alias и иметь пустой source; любой другой shape остаётся fail-closed; - provision/attest оба fixed data-fence inode из deploy под уже унаследованным exclusive codebase FD до runtime activation;
- оставить 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. Что в прежнем подходе было сделано неправильно
- Одновременный stale целых групп трактовался как поломка десятков API, хотя причинный признак указывал на потерянные scheduler slots.
- ProductSpec-файлы S2 принимались за фактический runtime. На S2 исполняются legacy-классы, поэтому сравнивать нужно именно их с S3 ProductSpec/plugins.
- Модульность
79/79ошибочно использовалась как доказательство parity. Она доказывает выбор runtime, но не идентичность запроса и данных. - Проверялись общие status/count раньше, чем exact request fingerprint, raw lineage, stable keys и coherent latest revision.
- Ручные catch-up запускались как восстановление, но не был сначала создан механизм, который сам замечает и ровно один раз восполняет пропущенный слот.
- Deploy/MCP/backup assurance выросли раньше, чем был закрыт базовый путь
schedule → request → intake → kernel → comparator. - Интеграционные тесты не запускали ETL под точным
gwptd_etlDB-контрактом, поэтомуNo database selectedдошёл до штатного cron. - До
3f1f152build_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 lifecycleMAX, YM revision inflation и legacy-формулы.
6. Зафиксированный scope
В scope
- 67 общих S2↔S3 endpoint-контрактов.
- 12 расширений S3 как отдельный extension scope; они не могут маскировать common parity.
- 25 job definitions, 75 scheduled ProductSpec и четыре exact unscheduled.
- Scoped kernel DB contract и атомарная публикация
build_all. - Девять data-gates: Orders, Stocks, Prices, Returns, Finance, Analytics, Storage, Turnover, Rating.
- Воспроизводимые 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 режим — быстро
- Создать checkpoint после утверждения этого плана.
- Зафиксировать SHA S2/S3, exact spec/pointer/schedule digests, последние natural runs, kernel build и comparator evidence.
- Остановить несвязанные 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
- Реализовать один явный default-schema contract одним из двух способов:
- recommended:
V3_MYSQL_DATABASE=gwptd_kernelв ETL wrapper и проводка значения черезconfig.pyвpymysql.connect(database=...); - либо полная квалификация всех temporary tables в пяти модулях, если default schema в handshake запрещена решением владельца.
- recommended:
- Одной совместимой волной обновить versioned migration, exact privilege
allowlist в
audit_etl_effective_privileges(), связанные deploy/control-plane contracts и regression tests. Разрешение — толькоCREATE TEMPORARY TABLES ON gwptd_kernel.*, не global privilege. - Общий 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. - Прогнать 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/events0; gwptd_kernel=724,107,264bytes; свободно на filesystem99,635,093,504bytes;- три физических slot заняли бы около 2.2 GB без запаса;
- active InnoDB transactions, current row waits и wait edges в момент
замера были
0; history list length0; - крупнейшие таблицы: 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.
Выбранная последовательность
- Первый containment-механизм — один pinned InnoDB transaction для всех 15 шагов, hard invariants и activation receipt.
- Если exact-copy performance/fault gate покажет неприемлемые undo, locks или rollback time, fallback — три фиксированных generation-slot schema и атомарное переключение stable proxy views/pointer.
- Прямой group
RENAME TABLE fact_*отклонён как первый вариант: он не охватывает dimensions, сложен с 29 FK, тремя view, metadata locks, grants и implicit DDL commit. - Ветка
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.shfail-closed отклоняет любое truthy/unknownV3_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/4green; - Ruff,
git diff --checkи architecture check green; active legacy files0.
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-writergwptd_etl@%на отдельныйgwptd_monitor@%. Principal имеет только точные table-levelSELECTи два comparatorINSERT; 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 доказательствами:
- S3 clean на exact
361845a; Docker app/API healthy,/new/login=200, root cron byte-exact, journal/failure/transaction markers отсутствуют; gwptd_monitor@%, root-owned secret/state files и все три exact lock inode аттестованы на S3; MCP receipt закрепил361845aи13 619points;- direct
next_collector.py --endpoint goldapple.snapshotзавершилсяrc=3с отсутствующим inherited codebase lock, directkernel.etl.build_all—rc=1с тем же fence до API/DB; freshness cron естественно стартовал в 12:45 UTC во время deploy и выполнилfreshness OKв 12:58 UTC после release lock.
Оставшиеся P1B gates — порядок работы
- P1B-2 rollout/deploy enforcement — DONE. Общий helper не переносится
без разбора в
_connect()/_cursor_cm(): ими пользуются также reference, monitor, preflight и historic paths с другой lock-семантикой. - 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/29raw/typed/lineage rows;2727записал 29 rows, но имел 28 successful subrequests и optionalHTTP -1, поэтому не может быть retroactively объявлен success. Во всех четырёхCollectionRun.finish()упал с MySQL1142, потому что bare joinFOR UPDATEпытался lock-нуть append-onlyraw_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. - 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 до этого не включается. - P1B-5 reader coherence. Реализация развернута, local disposable MySQL
proof зелёный:
SnapshotAPIRouteсоздаёт один lazy request-scopedREPEATABLE 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. - 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, пока эти элементы не доказаны.
- 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 S2master@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 доказывает67final/attested,0pending иp2_gate_closed=true; 12 S3 extensions остаются отделены. Строки сrequires_s3_canary/known_s3_driftнамеренно имеют dispositionfix_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 побайтно воспроизводит versionedcrontab.s3-next.txtи fail-closed запрещает произвольный shell/runner, несовпадающий endpointSet, неверный completion contract и изменение canonicalSHELL=/bin/bash/PATH. Static proof: 75 scheduled ProductSpec и четыре explicit unscheduled (amazon.buybox,amazon.sales_ranks,amazon.weekly_reports,wb.stocks). Workflow29518336839прошёл 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/claimedslots. Schema получает exact SHOW CREATE attestation; scheduler principal, launcher, timer/reconciler, P3-specific cron mutation и ledger rows остаются выключены.83c8a51прошёл CI и controlled S3 deploy workflow29528818504: exact DDL, пустые tables, отсутствие non-root direct grants/scheduler users, byte-exact root cron, healthy app/API и same-SHA MCP index14 760attested. Первый4f3f29ddeploy безопасно 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, а credentialgwptd_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.envroot: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-owned0755. Outer rollback вернул exact checkout и root cron. Исправленный candidate принимает0755; credential остаётсяroot:root 0600.
- Создать machine-readable
schedules/s3-next.yamlкак единственный источник job list, cron, freshness expectations и reconciler; versioned cron становится генерируемым artifact-ом и сравнивается с exact ROOT-crontab digest. - Создать 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. - Первый rollout начинает watermark с момента deploy и не переигрывает всю историю. Первый due-slot вычисляется из schedule registry. First-run-grace freshness даёт сценарии bootstrap, но не является due-time oracle.
- Cron и persistent systemd reconciler должны вызывать один atomic slot claim, а не быть двумя независимыми launcher-ами. Rollout выполняется двухфазно.
- Reconciler после reboot/deploy запускает ровно один bounded catch-up через
существующие locks/DB lease. Exit
75/8, активный lease или lock оставляет slot pending; duplicate launcher не создаётся. Возраст, attempts и API quota ограничены. - GA slots coalesce; daily/weekly/monthly сохраняют разную семантику. Ручной или natural run закрывает slot без повторного API-вызова только при exact-set и completion proof.
- Full deploy имеет absolute deadline до следующего защищённого slot и обязан восстановить расписание либо rollback до deadline.
- 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:
- Root provision receipt
/etc/gwptd/state/s3-next-deadline-bootstrap-dispatcher-provision.envфиксируетcandidate_sha=8a4c9ad, dispatcher SHAbf62a106…и initial outer SHA850c3f2…; оба совпадают с exact Git blobs. - Normal bootstrap receipt
/etc/gwptd/state/s3-next-deploy-deadline-bootstrap.envфиксируетnew_sha=e3e04d, current outer SHAc8c93aac…, helper SHA72e0106a…и exact service/timer SHA. Все пять installed файлов совпадают с receipt. gwptddeployимеетNOPASSWDтолько на/usr/local/sbin/gwptd-next-deploy; directsudo /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.
Локально реализованы следующие контракты:
- 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 originnext/spec-platform, fixed SSH transport, disables hooks/fsmonitor/replacement refs и читает source только как Git objects, а не из worktree. Каждая root-side Git операция получает это же изолированное окружение. - 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.
/etc/gwptd/state/s3-next-deploy-transaction.env— единственный canonical blocker и deadline contract. Root-owned cron preimage остаётся отдельным0600backup до завершённого recovery, но его SHA-256 записывается в canonical state; после удаления backup state всё ещё способен доказать restored crontab. State создаётся до snapshot cron.- Existing-transaction recovery делает rebind supervisor до любого fetch;
новый fetch bounded (
300s, TERM + 15s kill) и выполняется до создания transaction. Таким образом зависшая сеть не переживает durable deadline. - 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-chainlegacy → host → codebase → deadline;image_rollback_provenвосстанавливается только после exact old runtime и отсутствия control-plane before-image. Unproven inner/control-plane phases остаются fail-closed. - MCP/cron recovery идёт как durable handoff: state и backup не удаляются до
точного восстановления MCP, bridge path/timer и cron. Временный MCP failure
оставляет
deadline_recovery_*phase, root cron quarantine и retryable systemd exit75; только не доказанные состояния возвращают terminal124.rollback_in_progress,inner_deploy,image_replacement_activeи control-plane failures никогда не auto-resetятся watchdog-ом. complete_committed_deploy()проверяет каждый cleanup шаг явно. Effective systemd proof проверяетLoadState,FragmentPath, emptyDropInPaths, enabled timer и active state вместо текстовогоsystemctl cat.- Перед каждой независимой 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. - 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. - Local real-process regression now kills the outer process with
SIGKILLin a non-root Linux container, observes helperPDEATHSIG, verifies that every guard file is either attested A or B bytes, and proves the watchdog leaves the unproven state fail-closed. It passed1/1on Linux; the full local file is72 passed, 1 skippedon Darwin. This is still not an S3 live-fault or controlled-deploy proof. - A separate local two-process regression holds a temporary first canonical
lock and proves recovery cannot begin until the actual
flockcall is released; after release it observes the orderlegacy -> host -> codebase -> deadline. It uses no DB, Docker, systemd or host path. This is only a local lock contract, not live S3 contention evidence. - On 2026-07-18 a normal deployment at
61c3125exposed a separate MCP completion race: while post-deploy reindexing was in progress, GitHub advancednext/spec-platform; strict equality correctly left the transaction incompletion_unprovenand quarantined MCP and root cron. Commit7546178passes 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 passed72; workflow29651562797then completed a controlled normal deploy at772816a, 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 остаются обязательными:
- Controlled normal full deploy через установленный wrapper уже green для
exact
772816a(workflow29651562797), но он не инжектировал remote advance во время reindex. Для этой новой ветки нужен отдельный документируемый controlled proof либо эквивалентное live evidence; один normal deploy не даёт права считать race-path доказанным. - Отдельно выполнить документируемый 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 дня
Порядок и уже доказанные ограничения:
ozon.realization. S2 запрашивает текущий месяц и два предыдущих; S3monthsOffset: 1скрывает ожидаемый current-month404у posting и вместо этого собирает три прошлых месяца. Убрать offset можно только вместе с узким declarative exception: именноPOST /v1/finance/realization/posting, именно404, именно current calendar month = expected empty; historical404, totals404и malformed200остаются fail-closed. Отдельно нужен per-subrequest stable-key DSL либо endpoint остаётсяfix_s3: S2 хранитtotals:YYYY-MMи<report_number>:<row_num>, а S3 сейчас даётNone.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 defaultyour_share_pct DESCс детерминированным tie-breaker, а не global latest snapshot по date/category id.- Остальные
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 дней
Строгий порядок зависимостей:
- Primary: Orders → Stocks → Prices → Returns.
- Financial: Finance → Analytics → Storage.
- Derived: Turnover → Rating — только после зелёных входов.
| Gate | Обязательное доказательство |
|---|---|
| Orders | exact stable key, qty/price/revenue/status, duplicate 0, complete lineage |
| Stocks | common-scope exact, snapshot/retraction lineage, duplicate 0; mp10/history отдельно |
| Prices | пять price fields exact на common scope; GA/1C extensions отдельно |
| Returns | key/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 |
| Storage | coherent multiset sum, WB+Ozon+YM coverage, shuffle invariant; никакого false green MAX(id) |
| Turnover | ComparisonSpec v2, grain/lineage/formula digest, common window exact |
| Rating | ComparisonSpec 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 дней
- Три последовательных сопоставимых закрытых окна — early stability gate.
- Затем 14 последовательных natural G11 days без ручной подмены слотов.
- Weekly job должен естественно пройти внутри streak.
- Monthly Amazon требует отдельного естественного due-slot proof; 14 дней не превращают ещё не наступивший monthly slot в зелёный.
- Любое изменение formula/spec/schedule digest, partial build или unexplained parity сбрасывает streak.
Cutover остаётся отдельным решением владельца по
WAVE-7-S2-CUTOVER-RUNBOOK.md.
8. Риски, rollback и stop conditions
8.1. Риски и митигации
| Фаза | Риск | Обязательная митигация |
|---|---|---|
| P1 DB | global/лишний grant либо несовместимость code↔grant↔deploy audit | одна совместимая волна; только gwptd_kernel.*; exact envelope test |
| P1 DB | формальный env не выбирает schema | проводка config→PyMySQL и exact DATABASE() test либо полная квалификация |
| P1 publish | staging/swap блокирует readers, ломает FK/view или заполняет диск | design inventory, exact MySQL concurrency/fault tests, lock-timeout и retention |
| P3 | cron и 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/P4 | catch-up конкурирует с S2 за quota | bounded age/attempts, quota-window и stop при пересечении |
| P6 | повтор false green (MAX(id), incoherent revisions) | ComparisonSpec v2, multiset/lineage/shuffle-invariant |
| Все | dirty checkout или чужой writer | shared/exclusive runtime_codebase_lock.sh, clean checkpoint и digest attestation |
8.2. Rollback по фазам
- P0: runtime не меняется; неутверждённый evidence не продвигает gate.
- P1 DB:
ea7d5ffсохраняет exact grant preimage, проверяет afterimage и считает своим только scoped deltaCREATE TEMPORARY TABLES ON gwptd_kernel.*. Rollback отзывает его лишь при отсутствии иного drift и после доказанного отсутствия активного ETL; слепой globalREVOKEзапрещён. - 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 Oracle | read-only source/cron/log/DB evidence | запуск, deploy, cron/DB/secrets changes |
| S3 Kernel | P1, exact-principal tests, publish barrier | API drift и S2 writes |
| Contract + Scheduler | P2–P3, fixtures, ledger/reconciler tests | business formulas |
| Parity | P4–P6, ComparisonSpec/evidence | accepted differences и cutover |
| Docs/Evidence | registry, sanitized artifacts, handoff | runtime mutation |
Каждый поток отдаёт integrator-у: base SHA, changed paths, tests, live actions, rollback, unresolved blockers. Integrator не принимает незакоммиченный «мешок» из нескольких доменов.
10. Зафиксированные решения владельца
Владелец разрешил исполнение всего плана, commits, push и изменения S3. Поэтому нижеприведённые пункты считаются утверждёнными до отдельного изменения решения:
- Matrix/Qdrant/широкий refactor заморожены до P5.
- P1 kernel DB contract выполняется раньше дальнейших ручных collector-runs.
- Common-first обязателен: 67 S2 endpoint'ов проверяются отдельно от 12 расширений S3.
- Известные ошибки и ограничения S2 не копируются ради наивного count parity.
- Расписание восстанавливается через durable slot ledger и один reconciler, а не надежду на cron.
- Rating/Turnover не проверяются раньше исходных data-gates.
- До предложения cutover нужны три зелёных окна и затем 14 natural days.
- Для
gwptd_etlразрешён только schema-scopedCREATE TEMPORARY TABLES, а ETL-only capability preflight сохраняет строгий deploy privilege audit. - 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.