docs: record source validation and bounded dev acceptance
This commit is contained in:
89
docs/sources/2026-10-05-implementation-decisions.md
Normal file
89
docs/sources/2026-10-05-implementation-decisions.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Implementation decisions, 5 October 2026
|
||||
|
||||
Ordered ledger decisions and their costs; runtime gates remain pending.
|
||||
|
||||
- Ruling: stay in existing dev checkout per user branch instruction; no tracked unrelated modifications — avoids new branch/worktree without changing scope — cost if wrong: local dev contains this implementation.
|
||||
|
||||
- Task 1: Ruling: completed dataset has 16 headers, distinct from general 17; use confirmed separate mapping. Scope passport supports ended status; same-date completed observation outranks general while retaining both provenance — cost if wrong: overlapping IP misclassified; contradictory same-dataset rows reject.
|
||||
|
||||
- Task 3: Ruling: add FSSP artifact private-storage prefix; raw large legal datasets must not acquire public media URLs — follows existing private-artifact mechanism — cost if wrong: configured private root required on dev.
|
||||
|
||||
- Task 3: Ruling: settings.test disables all migrations; generate/check with MIGRATION_MODULES={} in the same isolated test-settings process, no user env changes — cost if wrong: migration drift could be missed without actual graph validation.
|
||||
|
||||
- Task 4: Ruling: extend snapshot_metadata and backend build/check-runtime scripts — aggregate history must exclude child CSVs, and the documented --check command treated its flag as a filename — cost if wrong: history/schema gate regressions; covered by aggregate and runtime gates.
|
||||
|
||||
- Task 4: Ruling: preserve publisher p. / p.p. reason text with ambiguous part/point null and warning; parse ISO termination date — verified full CSV labels differ from synthetic ch./p. mapping — cost if wrong: structured legal reason stays incomplete until mapping is verified.
|
||||
|
||||
- Task 4: Ruling: eight-hour task limit, disabled daily interval — two current 4.7GB inputs and streaming validation support bounded operation; full dev publication remains a separate gate — cost if wrong: slow environments can time out safely before publication.
|
||||
|
||||
- Task 4: Ruling: FSSP overflow pages return documented 200/empty while old groups retain existing 404; unsigned money behavior unchanged elsewhere — required frontend contract — cost if wrong: source-specific pagination differs, covered by wire tests.
|
||||
|
||||
- Task 4: Ruling: extend existing demo exclusions to FSSP instead of fabricating proceedings — real source results require snapshot artifacts, matching existing Fedresurs exclusion — cost if wrong: demo commands have no FSSP sample records.
|
||||
|
||||
- Task 1: Ruling: leasing is six verified /fedresurs event types, complete unfiltered pagination then filtering — one source claim, no undocumented contract fields — cost if wrong: richer contract details require another verified channel.
|
||||
|
||||
- Task 1: Ruling: own 100-page/10,000-row cap, provider limit=100 — explicit oversized failures preserve old records and bound quota — cost if wrong: very large issuers need an approved larger cap.
|
||||
|
||||
- Task 1: Ruling: documentation-derived synthetic fixtures suffice for implementation, selected-account access pending approved live probe — no paid requests in tests — cost if wrong: upstream deviations block readiness and require adapter fixes.
|
||||
|
||||
- Task 2: Ruling: CompanyResponse adds defaulted presence/raw flags and contextual license aliases rather than changing global aliases — keep existing client callers compatible while rejecting malformed section envelopes — cost if wrong: a provider schema change blocks collection until reverified.
|
||||
|
||||
- Task 3: Ruling: reuse paid-collector OPK/Rosatom/Roscosmos eligibility, require canonical import, valid ten-digit INN and thirteen/eight-digit OGRN/OKPO, unique head resolution — avoid paying for ambiguous or invalid directory rows — cost if wrong: invalid/branch identities remain preserved and need directory repair.
|
||||
|
||||
- Task 3: Ruling: extend private artifact routing to these sources and store streamed normalized observations with original upstream fields — never publish source details under MEDIA_ROOT — cost if wrong: another raw-envelope audit format may be required.
|
||||
|
||||
- Task 3: Ruling: fix existing publisher retained count independently of successful scope — prior overlapping filters reported zero preserved rows — cost if wrong: shared snapshot diagnostics could change, covered by FSSP/Fedresurs regressions.
|
||||
|
||||
- Task 4: Ruling: keep approved Checko machine IDs and verified provenance intact in new exports, preserve provider-neutral display text and prior-source sanitizer — source IDs/URLs cannot be changed by legacy presentation scrubber — cost if wrong: new provenance fields visibly identify their documented provider.
|
||||
|
||||
- Task 4: Ruling: export all history for these section groups; licence issuance year is not current validity — prevent valid older licences from disappearing in current-year exports — cost if wrong: selected section exports include historic messages too.
|
||||
|
||||
- Task 4: Ruling: exclude new sections from fabricated demo records; empty extensions remain — quota-aware sources need actual adapters rather than invented demo payloads — cost if wrong: demo previews need separately approved explicit fixtures.
|
||||
|
||||
- Task 4: Ruling: successful partial jobs expose counts but complete last-success excludes partial artifact metadata; all live records remain visible regardless batch — cost if wrong: changing eligibility leaves preserved old records until explicit future successful scope refresh.
|
||||
|
||||
- Task 1: Ruling: use issuer emitent_inn from documented securities response, never infer INN from numeric emitent_id — cost if wrong: unmapped issuer is skipped/quarantined rather than name-matched.
|
||||
|
||||
- Task 1: Ruling: replace obsolete XLSX plan with current official UTF-8 semicolon CSV; preserve strict observed 18 headers and use s_RTS_code, never Row/ISIN — verified official client export and 2287 unique codes — cost if wrong: upstream code changes reject/conflict; no guessed workbook channel.
|
||||
|
||||
- Task 1: Ruling: SPB custom CA approved only for probe/download, production collector stays default verified TLS — no extension of consent — cost if wrong: runtime SPB remains blocked until trust approval/configuration.
|
||||
|
||||
- Task 1: Ruling: MOEX shares and bonds reference pagination uses documented terminal empty, parameters/primary-board trading per exact canonical issuer; official init-dt selects dated duration response — cost if wrong: stale publisher date is preserved explicitly rather than guessed current.
|
||||
|
||||
- Task 1: Ruling: preserve effectiveyield raw Decimal string with unit null until field-specific unit proof; do not label current yield — insufficient direct unit proof — cost if wrong: readiness/unit remains pending though confirmed duration/channel implementation continues.
|
||||
|
||||
- Task 2: Ruling: add private stock_exchange_activity storage routing now rather than wait coordinator task — real download regression exposed public file URL — cost if wrong: all new raw/aggregate artifacts share one private prefix; no old source routing changed.
|
||||
|
||||
- Task 3: Ruling: retain complete bounded HTTP envelopes (body_utf8, params, URL, per-response SHA) in one private NDJSON input, including failed partial reads — original precision retained without one DB artifact per request — cost if wrong: replay needs reading NDJSON envelope; checksum/date still explicit.
|
||||
|
||||
- Task 3: Ruling: only exact canonical issuer triggers per-security parameter/trading HTTP, all reference pages still fully read/count; foreign/invalid INN counted — limits cost and no name matching — cost if wrong: missing authoritative issuer mapping remains diagnostic, not fabricated record.
|
||||
|
||||
- Task 4: Ruling: repeated exchange-prefixed vendor IDs reject whole source, including exact duplicate rows — fail closed because reference/current export verifies uniqueness — cost if wrong: harmless upstream duplicates require an explicit dedup policy before publication.
|
||||
|
||||
- Task 5: Ruling: add source refresh typed error envelope and arbitrary details mapping rather than accept generated Zod mutation — actual 403/400/404 differed from stale CommonResponses — cost if wrong: generated frontend error types change to match observed runtime, no runtime error behavior change.
|
||||
|
||||
- Task 5: Ruling: exchange export all current records regardless listing year and private unmodified provenance, exclude fabricated demo records — securities remain listed across years, fixtures do not prove real listing — cost if wrong: export includes older instruments and demo needs explicit separately approved samples.
|
||||
|
||||
- Task 5: Ruling: disabled daily schedule template and eight-hour limit only; local API/code gate separated from live readiness — preserves external authorization boundary — cost if wrong: runtime acceptance still required before enabling source.
|
||||
|
||||
- Task 5: Ruling: finish all authorized local implementation/review now, retain SPB default TLS + MOEX HTML403 + yield-unit uncertainty as readiness gates; paid account and remote DB/deploy await bounded approval — mock/public subset evidence cannot prove complete dev publication — cost if wrong: five sources remain not-ready until exact live acceptance.
|
||||
|
||||
- Final: Ruling: canonical FSSP/exchange OGRN and OKPO require 13/8 digits before publication — enforce existing authoritative requisites contract without repair or new organizations — cost if wrong: incomplete canonical records remain quarantined until directory repair.
|
||||
|
||||
- Final: Ruling: actual Checko account/tariff/live compatibility remains pending bounded authorized acceptance — documentation-derived fixtures prove local logic only — cost if wrong: account or schema mismatch blocks live data.
|
||||
|
||||
- Final: Ruling: SPB runtime trust stays unchanged; approved CA applies to public probe/download only — user scope is explicit — cost if wrong: production collector cannot yet retrieve SPB.
|
||||
|
||||
- Final: Ruling: MOEX HTML403 and effectiveyield unit null remain explicit readiness gates — no WAF bypass or guessed units — cost if wrong: combined snapshot cannot publish until verified channel is available.
|
||||
|
||||
- Final: Ruling: full canonical dev publication, staging scale and live API/export remain unverified — local reader/PostgreSQL evidence cannot establish remote population/performance — cost if wrong: capacity or matching failures require dev acceptance before ready.
|
||||
|
||||
- Final: Ruling: deployment, schedules and production operation remain deferred — push dev triggers deployment and is outside local authorization — cost if wrong: local code exists without operational rollout.
|
||||
|
||||
- Final: Ruling: valid-header empty CSV remains genuine empty under approved plan, with no independent publisher count — no invented completeness signal — cost if wrong: semantic header-only upstream truncation can clear existing rows and is a documented limit.
|
||||
|
||||
- Final: Ruling: frontend rendering, StateCorp and root behavior remain outside scope — frontend only updated from Git per user and no code changes — cost if wrong: frontend-specific acceptance remains with its owner.
|
||||
|
||||
- Final: Ruling: keep existing dev checkout as explicitly chosen by user; adapt finishing-branch menu rather than merge dev into itself or create unrequested PR — no push/deploy implied — cost if wrong: integration awaits explicit external authorization.
|
||||
|
||||
Deferred minors: none. All three Important reviewer findings were fixed with watched RED→GREEN regressions.
|
||||
123
docs/sources/2026-10-05-implementation-handoff.md
Normal file
123
docs/sources/2026-10-05-implementation-handoff.md
Normal file
@@ -0,0 +1,123 @@
|
||||
# Передача пяти источников, 5 октября 2026
|
||||
|
||||
Локальная реализация в `mostovik-backend/dev` завершена. Реальное наполнение dev
|
||||
и включение расписаний не выполнены. Frontend обновлён из Git ранее в этой работе,
|
||||
его код не менялся. StateCorp, root repo, env и submodule pointers не коммитились.
|
||||
|
||||
| Источник | Карточка | source_group | record_type |
|
||||
| --- | --- | --- | --- |
|
||||
| fssp_enforcement_proceedings | fssp-enforcement-proceedings | enforcement_proceedings | enforcement_proceeding |
|
||||
| checko_leasing | checko-leasing | leasing | leasing_contract |
|
||||
| checko_messages | checko-messages | company_messages | company_message |
|
||||
| checko_licenses | checko-licenses | company_licenses | company_license |
|
||||
| stock_exchange_activity | stock-exchange-activity | stock_exchange_activity | exchange_instrument |
|
||||
|
||||
СПБ и MOEX — одна карточка/источник; поле `payload.exchange=spb|moex` различает
|
||||
записи. ФССП последняя карточка, item code `fssp_inn_search`. Привязка только к
|
||||
каноническому справочнику по точным реквизитам; организации не создаются.
|
||||
|
||||
## Контракт для frontend
|
||||
|
||||
- `GET /api/v1/sources/` и `/api/v1/sources/<slug>/`: карточки, счётчики,
|
||||
последний job/load и последний полный успешный snapshot.
|
||||
- `POST /api/v1/sources/<slug>/refresh/`: только администратор, пустой JSON;
|
||||
202 принят, 400 некорректные параметры, 403 нет прав, 404 карточка отсутствует,
|
||||
409 этот источник уже запущен. File URLs от пользователя не принимаются.
|
||||
- `GET /api/v2/organization-source-records/?source_group=<group>`;
|
||||
detail `/api/v2/organization-source-records/<uid>/`. Общие фильтры source,
|
||||
record_type, organization, search, date_from/date_to, ordering, page/page_size.
|
||||
Поля payload и ordering перечислены в документах каждого источника.
|
||||
- Биржи: `exchange=moex|spb`, `instrument_kind`; номинал, yield, duration —
|
||||
отдельные nullable metrics, `amount=null`. MOEX effectiveyield сохранён под
|
||||
своим именем в provenance, его unit пока null; duration unit=days.
|
||||
- ФССП: `amount=debt_amount`, signed decimal string; claim отдельно. Отрицательное
|
||||
значение и ноль не заменяются null. Будущие даты сохраняются с warnings.
|
||||
Выход за последнюю страницу возвращает 200/пустой массив.
|
||||
- Checko: суммы договоров и полный текст сообщения не выдумываются; amount null.
|
||||
Истечение даты лицензии не используется как доказательство её прекращения.
|
||||
- CSV/XLSX/JSON через существующие export-ticket/generation API сохраняют текущий
|
||||
snapshot независимо от года ИП, выдачи лицензии или listing. UUID совпадают с
|
||||
list/detail; ранее выданный ticket привязан к своей generation.
|
||||
|
||||
Canonical contract: `src/core/openapi.json`; generator и инструкции —
|
||||
`tools/openapi/README.md`. Новые SourceRefresh error DTO отражают реальный envelope,
|
||||
включая произвольные details. 43 синтетических отрендеренных HTTP-ответа проверены
|
||||
generated Orval/Zod без изменения/потери полей. Frontend генерация не запускалась.
|
||||
|
||||
## Публикация и отказы
|
||||
|
||||
ФССП требует два полных файла, биржи — оба полных входа. Staging batches ≤500,
|
||||
публикация атомарна; ошибка сохраняет прежний snapshot и last-success.
|
||||
Raw/manifest приватны. Повторяющиеся биржевые vendor IDs отвергают весь snapshot.
|
||||
|
||||
Checko использует один необратимый месячный claim на organization/source до
|
||||
первого HTTP. Полная пагинация проверяет одновременно количество полученных строк
|
||||
и уникальных GUID **до фильтра лизинга**. Пересечение страниц при заявленном total
|
||||
не считается полным результатом; прежние записи такой организации сохраняются,
|
||||
attempt failed. Partial job показывает counters, но не двигает полный last-success.
|
||||
|
||||
## Итоговая локальная проверка
|
||||
|
||||
Один независимый whole-branch reviewer: 0 Critical, 3 Important, 0 Minor.
|
||||
Все три Important воспроизведены тестами RED и исправлены GREEN:
|
||||
пересечение страниц Checko, завершение MOEX cursor pagination на TOTAL и экспорт
|
||||
ФССП с предыдущим/будущим годом начала ИП. Повторный reviewer не запускался.
|
||||
|
||||
- Полный suite, кроме отдельно проверенного API inventory: **1922 passed,
|
||||
44 skipped, 13 warnings**. Пропуски не считаются успешными проверками.
|
||||
- PostgreSQL с `--migrations`: исправления и связанные сценарии **72 passed,
|
||||
0 skipped**. Ранее отдельный `--migrations --create-db`: **66 passed**,
|
||||
граф применён до parsers 0047 / organizations 0018; admission/export 64 passed.
|
||||
- API inventory: **9 passed с явно подменённым async dispatch**. Это проверка
|
||||
HTTP surface, а не выполнение настоящих Celery задач/полный CI без подмены.
|
||||
- Ruff src и format всех 235 src файлов, Django check, canonical OpenAPI,
|
||||
strict TypeScript, Zod **43 responses**, git diff --check — PASS.
|
||||
- Обычные настройки pytest содержат `--nomigrations`: прежние утверждения о
|
||||
применении графа в этих прогонах были неточны; фактическое применение доказано
|
||||
отдельными указанными выше прогонами с `--migrations`.
|
||||
|
||||
Полные публичные ФССП inputs: **7 066 820 строк, 4 695 702 827 байт**, оба EOF/SHA
|
||||
проверены. СПБ: **2287 строк**, 251 с корректным ИНН. MOEX reference: shares 526,
|
||||
bonds 3175; dated durations 2478; одна реальная бумага проверена по parameters и
|
||||
primary-board trading. MOEX probe использовал дату из ранее проверенного HTML:
|
||||
повторная загрузка самой страницы вернула 403. Это не полный worker acceptance.
|
||||
Подробные hashes и ограничения — в [ФССП](fssp.md),
|
||||
[Checko](checko-sections.md), [биржах](exchanges.md).
|
||||
|
||||
## Конкретный следующий этап: dev acceptance
|
||||
|
||||
Этот этап подготовлен, **не выполнен и не разрешён текущей локальной разработкой**.
|
||||
Push `dev` запускает CI/CD из `.gitea/workflows/ci-cd.yml`, включая web/celery release.
|
||||
Следовать актуальному root `DEPLOYMENT.md` и `deploy/ecos-dev/README.md`,
|
||||
а не его историческим privileged SSH процедурам. Проверить точные commit/digests,
|
||||
CI и соответствие web/celery, migrations через штатный release wrapper.
|
||||
|
||||
1. Только Mostovik backend; все пять новых schedules оставлять disabled.
|
||||
До записи проверить текущий private storage и свободное место: raw ФССП уже
|
||||
4.7 GB, staging/manifest/exports требуют дополнительного измеренного запаса.
|
||||
Проверить worker limits и однозначность canonical directory. Сделать
|
||||
согласованный backup затрагиваемых published records/artifacts.
|
||||
2. Один ручной полный ФССП refresh через admin API, без переданных URL.
|
||||
Зафиксировать job, оба SHA/версии, matched/skipped/quarantine/published counts,
|
||||
сохранение UID, list/detail signed/null fields и prepared export generation.
|
||||
Обрыв/отказ не должен менять старую публикацию; сравнивать с backup.
|
||||
3. Checko: сначала согласовать аккаунт/тариф и денежный лимит, затем одна
|
||||
однозначная eligible canonical организация, три раздела. Предлагаемый потолок
|
||||
пробы **11 HTTP: 1 company + ≤5 messages pages + ≤5 leasing pages**. Это
|
||||
ограничение будущего transport wrapper, не существующий CLI параметр:
|
||||
обычный refresh проходит весь eligible scope и до 100 pages/source/org,
|
||||
его нельзя использовать для этой ограниченной пробы. При исчерпании бюджета
|
||||
отказ до следующего HTTP, staging discard, claim остаётся; полный обход
|
||||
отдельно после оценки всей eligible population. Денежная стоимость неизвестна.
|
||||
4. Биржи: runtime trust СПБ отдельно согласовать; имеющееся разрешение CA касается
|
||||
только уже проведённой публичной проверки/загрузки. Сначала подтвердить
|
||||
доступность MOEX durations HTML из worker и единицу effectiveyield официальным
|
||||
field-specific источником. Затем один полный combined refresh, отдельные
|
||||
counters входов, единый publish/list/detail/export. Не обходить TLS/WAF.
|
||||
5. Только после этой приёмки источники можно объявлять ready; включение schedules
|
||||
отдельно. Frontend изменения, StateCorp, main и Telegram sends вне этапа.
|
||||
|
||||
Header-only CSV с подтверждёнными headers трактуется как пустой по согласованному
|
||||
плану. Независимого publisher row count нет: semantic truncation до одних headers
|
||||
не доказуем существующим каналом и может очистить записи при формально полном
|
||||
пустом snapshot. Это сохраняемый предел проверки, не установленный live факт.
|
||||
@@ -35,4 +35,4 @@ Claim берётся атомарно до первого запроса и со
|
||||
|
||||
Artifact — приватный NDJSON с нормализованными наблюдениями и upstream-полями, SHA-256/size; credentials/meta balance не сохраняются. `completeness=full|partial`; непересекающиеся категории: `organizations_updated + organizations_empty + organizations_failed + quota_skipped = organizations_total`. `organizations_preserved = organizations_failed + quota_skipped`, это пересекающийся диагностический счётчик, его не суммируют второй раз. `updated_records_count` — записи завершённого scope, `retained_records_count` — сохранённые записи, published/snapshot counts — весь текущий опубликованный набор. Partial success не двигает `latest_success_load` полного прохода; последний job/load показывает partial metadata. API и экспорт читают все текущие записи, включая сохранённые из прежних batches.
|
||||
|
||||
Локальная проверка 05.10.2026: adapters/старый клиент/local HTTP — 126 passed; PostgreSQL с настоящими миграциями/гонкой monthly claim и admission/export — 42 passed; generated OpenAPI/Orval/type-check и Zod round-trip — 19 фактических JSON-ответов без изменения/потери полей. Платные реальные вызовы не выполнялись. Ограниченная dev-проба и полный обход — отдельные критерии готовности.
|
||||
Итоговая проверка и конкретная dev-приёмка — в [передаче реализации](2026-10-05-implementation-handoff.md). Прежние PostgreSQL 42 passed проверяли schema/locks, но использовали pytest `--nomigrations`; фактический граф доказан позднее отдельным `--migrations --create-db` прогоном. Пересечение страниц с неполным числом уникальных GUID теперь отклоняется до публикации и до фильтра лизинга; старые записи и месячный claim сохраняются. Платные реальные вызовы не выполнялись.
|
||||
|
||||
@@ -98,3 +98,8 @@ CSV/XLSX/JSON exports через штатные generations/tickets сохран
|
||||
|
||||
Реальный canonical dev publish/API/export, доступ Checko и production TLS trust СПБ
|
||||
не выполнены. Нет push/deploy и changes в frontend/StateCorp/root/env.
|
||||
|
||||
Финальное ревью и итоговые проверки — в [передаче реализации](2026-10-05-implementation-handoff.md).
|
||||
Если ISS возвращает cursor, обход завершён после валидированной страницы,
|
||||
достигшей TOTAL; для ответов без cursor сохраняется terminal-empty обход.
|
||||
Регрессии TOTAL=1/100/101 прошли после воспроизведения ошибки.
|
||||
|
||||
@@ -56,3 +56,10 @@ Checksums:
|
||||
Локальные проверки: полный pytest без inventory E2E — 1 809 passed, 39 skipped (PostgreSQL-only и opt-in случаи), 13 warnings. После последней проверки обязательных реквизитов — 24 адресных tests passed. Scoped Ruff/format, Django check, migration graph/check и canonical OpenAPI/Orval/type-check прошли; generated Zod сохранил 13 runtime JSON responses без потери ключей. List/detail/signed/null/date/order/permission/duplicate refresh и pinned export tickets проверены на синтетических fixtures, не на удалённом API.
|
||||
|
||||
Readiness: implemented, full upstream reader verified; full dev snapshot publication/API/export acceptance pending. Daily schedule disabled. Нельзя включать расписание до согласованного полного dev запуска с rollback/UUID/manifest/counters проверкой. Frontend без изменений.
|
||||
|
||||
Итоговые проверки после независимого ревью — в [передаче реализации](2026-10-05-implementation-handoff.md).
|
||||
Экспорт текущего snapshot теперь включает ИП прежних и будущих лет начала, как
|
||||
list/detail: год initiation не определяет наличие ИП в актуальной выгрузке.
|
||||
Canonical OGRN/OKPO проверяются на 13/8 цифр; неполные/неоднозначные реквизиты
|
||||
не исправляются парсером. Реальное применение migrations доказано отдельным
|
||||
pytest с `--migrations`; обычный test profile использует `--nomigrations`.
|
||||
|
||||
Reference in New Issue
Block a user