fix: accept nullable message publishers and scoped dev SPB trust
Some checks failed
Mostovik Backend CI/CD / Tests and lint (push) Successful in 3m3s
Mostovik Backend CI/CD / Deploy dev (push) Has been cancelled
Mostovik Backend CI/CD / Deploy and verify internal main (push) Has been cancelled
Mostovik Backend CI/CD / Build linux/amd64 release images (push) Has been cancelled
Some checks failed
Mostovik Backend CI/CD / Tests and lint (push) Successful in 3m3s
Mostovik Backend CI/CD / Deploy dev (push) Has been cancelled
Mostovik Backend CI/CD / Deploy and verify internal main (push) Has been cancelled
Mostovik Backend CI/CD / Build linux/amd64 release images (push) Has been cancelled
This commit is contained in:
@@ -98,3 +98,24 @@ readiness remains separate from enablement.
|
|||||||
already-applied and fresh databases — cost if wrong: 0048 must apply to activate.
|
already-applied and fresh databases — cost if wrong: 0048 must apply to activate.
|
||||||
- Ruling: retain daily FSSP/exchange and 30-day Checko intervals/monthly claims —
|
- Ruling: retain daily FSSP/exchange and 30-day Checko intervals/monthly claims —
|
||||||
minimal requested change — cost if wrong: 30-day cadence is not a calendar month.
|
minimal requested change — cost if wrong: 30-day cadence is not a calendar month.
|
||||||
|
|
||||||
|
## Live acceptance continuation
|
||||||
|
|
||||||
|
- Ruling: accept nullable Checko publisher only when the canonical subject still
|
||||||
|
matches the publisher or an exact participant — observed real upstream null,
|
||||||
|
no invented identifier — cost if wrong: messages without confirmed subject
|
||||||
|
remain rejected; generated clients must accept null.
|
||||||
|
- Ruling: preserve specific SnapshotValidationError before its ValueError base
|
||||||
|
handler — real diagnostics otherwise conceal the rejected field — cost if
|
||||||
|
wrong: safe error codes become more specific for existing rejected inputs.
|
||||||
|
- Ruling: stop the broken messages run cooperatively, keep all monthly claims,
|
||||||
|
and rerun only eligible unclaimed scopes after release — avoids repeated costs
|
||||||
|
for known adapter failures — cost if wrong: first-month coverage stays partial.
|
||||||
|
- Ruling: use the two already verified official FSSP daily files for separate
|
||||||
|
manual import acceptance when dev receives HTTP 474 — no network bypass or
|
||||||
|
invented freshness — cost if wrong: manual publication does not prove the
|
||||||
|
automatic upstream download is operational.
|
||||||
|
- Ruling: enable the existing Russian CA only in SPB's dedicated allowlisted
|
||||||
|
session behind a default-off setting and a dev-only host compose flag after
|
||||||
|
explicit user consent — cost if wrong: only SPB gains this extra trust;
|
||||||
|
MOEX/system/main trust remains unchanged, certificate verification stays on.
|
||||||
|
|||||||
@@ -36,3 +36,25 @@ 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.
|
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.
|
||||||
|
|
||||||
Итоговая проверка и конкретная dev-приёмка — в [передаче реализации](2026-10-05-implementation-handoff.md). Прежние PostgreSQL 42 passed проверяли schema/locks, но использовали pytest `--nomigrations`; фактический граф доказан позднее отдельным `--migrations --create-db` прогоном. Пересечение страниц с неполным числом уникальных GUID теперь отклоняется до публикации и до фильтра лизинга; старые записи и месячный claim сохраняются. Платные реальные вызовы не выполнялись.
|
Итоговая проверка и конкретная dev-приёмка — в [передаче реализации](2026-10-05-implementation-handoff.md). Прежние PostgreSQL 42 passed проверяли schema/locks, но использовали pytest `--nomigrations`; фактический граф доказан позднее отдельным `--migrations --create-db` прогоном. Пересечение страниц с неполным числом уникальных GUID теперь отклоняется до публикации и до фильтра лизинга; старые записи и месячный claim сохраняются. Платные реальные вызовы не выполнялись.
|
||||||
|
|
||||||
|
## Реальный dev запуск 5 октября 2026
|
||||||
|
|
||||||
|
Пользователь разрешил ручной полный сбор. Лизинг опубликовал 3 158 записей:
|
||||||
|
3 236 организаций успешно завершены, 2 523 запроса завершились отказом,
|
||||||
|
269 некорректных/неоднозначных канонических организаций не запрашивались.
|
||||||
|
Этот результат partial; полный last-success не подменяется. Read-only проверка
|
||||||
|
развёрнутых DRF list/detail против реальной БД подтвердила pagination total,
|
||||||
|
UUID и совпадение payload. Внешний запрос без аутентификации возвращает 401.
|
||||||
|
|
||||||
|
Реальный `/fedresurs` также возвращает `Публикатор: null` при наличии нашего
|
||||||
|
ИНН/ОГРН в `Участники`. Ранее адаптер ошибочно отклонял весь раздел такой
|
||||||
|
организации. Publisher теперь nullable, принадлежность по точному участнику
|
||||||
|
сохраняется обязательной, если publisher не совпадает. Null сохраняется в raw,
|
||||||
|
list/detail и canonical OpenAPI. Ошибки SnapshotValidationError сохраняют
|
||||||
|
конкретную безопасную причину вместо общего invalid_checko_section_schema.
|
||||||
|
|
||||||
|
Месячные claims после первого прогона и остановленного сбора сообщений
|
||||||
|
сохраняются. Исправление не разрешает их сброс, повторную оплату или фиктивную
|
||||||
|
публикацию неуспешных организаций. Последующий штатный запуск обработает только
|
||||||
|
ещё не заявленные организации; полный охват потребует следующего периода либо
|
||||||
|
отдельно согласованной политики повторного сбора.
|
||||||
|
|||||||
@@ -103,3 +103,17 @@ CSV/XLSX/JSON exports через штатные generations/tickets сохран
|
|||||||
Если ISS возвращает cursor, обход завершён после валидированной страницы,
|
Если ISS возвращает cursor, обход завершён после валидированной страницы,
|
||||||
достигшей TOTAL; для ответов без cursor сохраняется terminal-empty обход.
|
достигшей TOTAL; для ответов без cursor сохраняется terminal-empty обход.
|
||||||
Регрессии TOTAL=1/100/101 прошли после воспроизведения ошибки.
|
Регрессии TOTAL=1/100/101 прошли после воспроизведения ошибки.
|
||||||
|
|
||||||
|
## Dev trust acceptance, 5 October 2026
|
||||||
|
|
||||||
|
Реальный штатный job на dev получил SSLError от СПБ. Пользователь явно разрешил
|
||||||
|
повторное использование существующего bundle Минцифры именно сборщиком СПБ на dev.
|
||||||
|
`EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED` по умолчанию false. При true только отдельная
|
||||||
|
SPB session использует `clients/common/eis_russian_trusted_ca.pem`; все её запросы
|
||||||
|
проходят существующий allowlist spbexchange.ru. MOEX session, другие источники и
|
||||||
|
системное хранилище не меняются; verify=False отсутствует.
|
||||||
|
|
||||||
|
Оператор включает этот несекретный флаг только в Mostovik environment anchor
|
||||||
|
host-owned compose dev, с резервной копией, release lock и config --quiet
|
||||||
|
проверкой до штатного CI release. Root checkout/StateCorp/main не изменяются.
|
||||||
|
Флаг не включается автоматически при последующем развёртывании в другом контуре.
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ def _message_record(raw, organization, source, fetched_at):
|
|||||||
guid = _text(raw.get("GUID"), required=True)
|
guid = _text(raw.get("GUID"), required=True)
|
||||||
message_type = _text(raw.get("Тип"), required=True)
|
message_type = _text(raw.get("Тип"), required=True)
|
||||||
label = _text(raw.get("ТипНаим"))
|
label = _text(raw.get("ТипНаим"))
|
||||||
publisher = _text(raw.get("Публикатор"), required=True)
|
publisher = _text(raw.get("Публикатор"))
|
||||||
participants = raw.get("Участники")
|
participants = raw.get("Участники")
|
||||||
if not isinstance(participants, list):
|
if not isinstance(participants, list):
|
||||||
raise SnapshotValidationError("invalid_checko_participants")
|
raise SnapshotValidationError("invalid_checko_participants")
|
||||||
@@ -259,5 +259,7 @@ def collect_checko_section(
|
|||||||
raise SnapshotValidationError(
|
raise SnapshotValidationError(
|
||||||
f"checko_collection_failed:{type(exc).__name__}"
|
f"checko_collection_failed:{type(exc).__name__}"
|
||||||
) from exc
|
) from exc
|
||||||
|
except SnapshotValidationError:
|
||||||
|
raise
|
||||||
except (ValueError, TypeError, KeyError) as exc:
|
except (ValueError, TypeError, KeyError) as exc:
|
||||||
raise SnapshotValidationError("invalid_checko_section_schema") from exc
|
raise SnapshotValidationError("invalid_checko_section_schema") from exc
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from io import BytesIO, TextIOWrapper
|
|||||||
from typing import BinaryIO
|
from typing import BinaryIO
|
||||||
from urllib.parse import urljoin, urlparse
|
from urllib.parse import urljoin, urlparse
|
||||||
|
|
||||||
|
from apps.parsers.clients.common.structured import EIS_CA_BUNDLE_PATH
|
||||||
from apps.parsers.models import ParserSourceArtifact
|
from apps.parsers.models import ParserSourceArtifact
|
||||||
from apps.parsers.registry_http import (
|
from apps.parsers.registry_http import (
|
||||||
limited_bytes,
|
limited_bytes,
|
||||||
@@ -170,7 +171,9 @@ def download_spb_artifact(
|
|||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
with registry_session() as session:
|
with registry_session() as session:
|
||||||
# Existing EIS trust is deliberately NOT reused: approval was probe-only.
|
# This session serves only allowlisted SPB requests; MOEX has its own.
|
||||||
|
if getattr(settings, "EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED", False):
|
||||||
|
session.verify = str(EIS_CA_BUNDLE_PATH)
|
||||||
with registry_response(session, SPB_INDEX, hosts=SPB_HOSTS) as response:
|
with registry_response(session, SPB_INDEX, hosts=SPB_HOSTS) as response:
|
||||||
before = discover_spb_date(
|
before = discover_spb_date(
|
||||||
limited_bytes(response, 4 * 1024**2).decode("utf-8")
|
limited_bytes(response, 4 * 1024**2).decode("utf-8")
|
||||||
|
|||||||
@@ -22194,7 +22194,8 @@
|
|||||||
"nullable": true
|
"nullable": true
|
||||||
},
|
},
|
||||||
"publisher_identifier": {
|
"publisher_identifier": {
|
||||||
"type": "string"
|
"type": "string",
|
||||||
|
"nullable": true
|
||||||
},
|
},
|
||||||
"participant_identifiers": {
|
"participant_identifiers": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
@@ -22258,7 +22259,8 @@
|
|||||||
"nullable": true
|
"nullable": true
|
||||||
},
|
},
|
||||||
"publisher_identifier": {
|
"publisher_identifier": {
|
||||||
"type": "string"
|
"type": "string",
|
||||||
|
"nullable": true
|
||||||
},
|
},
|
||||||
"participant_identifiers": {
|
"participant_identifiers": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class CheckoMessagePayloadSerializer(serializers.Serializer):
|
|||||||
publication_date = serializers.DateField(allow_null=True)
|
publication_date = serializers.DateField(allow_null=True)
|
||||||
message_type = serializers.CharField()
|
message_type = serializers.CharField()
|
||||||
message_type_name = serializers.CharField(allow_null=True)
|
message_type_name = serializers.CharField(allow_null=True)
|
||||||
publisher_identifier = serializers.CharField()
|
publisher_identifier = serializers.CharField(allow_null=True)
|
||||||
participant_identifiers = serializers.ListField(child=serializers.CharField())
|
participant_identifiers = serializers.ListField(child=serializers.CharField())
|
||||||
source_url = serializers.CharField(allow_null=True)
|
source_url = serializers.CharField(allow_null=True)
|
||||||
fetched_at = RegistryUTCDateTimeField()
|
fetched_at = RegistryUTCDateTimeField()
|
||||||
|
|||||||
@@ -532,6 +532,9 @@ SRO_MAX_REQUESTS_PER_RUN = int(os.getenv("SRO_MAX_REQUESTS_PER_RUN", "10000"))
|
|||||||
# Public exchange collection bounds; TLS verification stays enabled.
|
# Public exchange collection bounds; TLS verification stays enabled.
|
||||||
EXCHANGE_SPB_MAX_BYTES = 50 * 1024**2
|
EXCHANGE_SPB_MAX_BYTES = 50 * 1024**2
|
||||||
EXCHANGE_SPB_MAX_ROWS = 100000
|
EXCHANGE_SPB_MAX_ROWS = 100000
|
||||||
|
EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED = _env_bool(
|
||||||
|
"EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED", default=False
|
||||||
|
)
|
||||||
EXCHANGE_MOEX_MAX_RESPONSE_BYTES = 10 * 1024**2
|
EXCHANGE_MOEX_MAX_RESPONSE_BYTES = 10 * 1024**2
|
||||||
EXCHANGE_MOEX_MAX_PAGES = 1000
|
EXCHANGE_MOEX_MAX_PAGES = 1000
|
||||||
EXCHANGE_MOEX_MAX_REQUESTS = 10000
|
EXCHANGE_MOEX_MAX_REQUESTS = 10000
|
||||||
|
|||||||
@@ -151,6 +151,27 @@ class CheckoSectionContractTests(TestCase):
|
|||||||
== "partial"
|
== "partial"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_nullable_publisher_survives_public_list_and_detail(self):
|
||||||
|
first = fixture("messages-page-1.json")
|
||||||
|
first["data"]["Записи"][0]["Публикатор"] = None
|
||||||
|
with patch.object(
|
||||||
|
snapshots,
|
||||||
|
"_client",
|
||||||
|
return_value=client_with(first, fixture("messages-page-2.json")),
|
||||||
|
):
|
||||||
|
snapshots.refresh_checko_section(source="checko_messages", load_batch=1)
|
||||||
|
response = self.client.get(self.url, {"source_group": "company_messages"})
|
||||||
|
assert response.status_code == 200, response.data
|
||||||
|
row = next(
|
||||||
|
row
|
||||||
|
for row in response.data["data"]
|
||||||
|
if row["payload"]["publisher_identifier"] is None
|
||||||
|
)
|
||||||
|
detail = self.client.get(self.url + row["uid"] + "/")
|
||||||
|
assert detail.status_code == 200, detail.data
|
||||||
|
assert detail.data["payload"] == row["payload"]
|
||||||
|
assert row["payload"]["participant_identifiers"] == [self.org.inn]
|
||||||
|
|
||||||
def test_no_completed_failure_exposes_rejected_counters(self):
|
def test_no_completed_failure_exposes_rejected_counters(self):
|
||||||
source = "checko_messages"
|
source = "checko_messages"
|
||||||
claim_monthly_collection(organization_id=str(self.org.uid), source=source)
|
claim_monthly_collection(organization_id=str(self.org.uid), source=source)
|
||||||
|
|||||||
@@ -141,12 +141,12 @@ def _canonical_records():
|
|||||||
)
|
)
|
||||||
sections = []
|
sections = []
|
||||||
for source in ("checko_leasing", "checko_messages", "checko_licenses"):
|
for source in ("checko_leasing", "checko_messages", "checko_licenses"):
|
||||||
|
message_page = fixture("messages-page-1.json")
|
||||||
|
message_page["data"]["Записи"][0]["Публикатор"] = None
|
||||||
client = (
|
client = (
|
||||||
client_with(fixture("license.json"))
|
client_with(fixture("license.json"))
|
||||||
if source == "checko_licenses"
|
if source == "checko_licenses"
|
||||||
else client_with(
|
else client_with(message_page, fixture("messages-page-2.json"))
|
||||||
fixture("messages-page-1.json"), fixture("messages-page-2.json")
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
row = next(collect_checko_section(client, organization=fssp_org, source=source))
|
row = next(collect_checko_section(client, organization=fssp_org, source=source))
|
||||||
row.payload["upstream"]["future_nested"] = {
|
row.payload["upstream"]["future_nested"] = {
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ def test_overlapping_pages_cannot_prove_total_before_leasing_filter(source):
|
|||||||
response["data"]["ЗапВсего"] = 4
|
response["data"]["ЗапВсего"] = 4
|
||||||
with pytest.raises(SnapshotValidationError) as error:
|
with pytest.raises(SnapshotValidationError) as error:
|
||||||
collect(client_with(first, second), source)
|
collect(client_with(first, second), source)
|
||||||
assert str(error.value.__cause__) == "incomplete_checko_record_count"
|
assert str(error.value) == "incomplete_checko_record_count"
|
||||||
|
|
||||||
|
|
||||||
def test_license_unknown_raw_fields_survive():
|
def test_license_unknown_raw_fields_survive():
|
||||||
@@ -200,3 +200,23 @@ def test_malformed_license_section_rejected(value):
|
|||||||
response["data"]["Лиценз"] = value
|
response["data"]["Лиценз"] = value
|
||||||
with pytest.raises(SnapshotValidationError):
|
with pytest.raises(SnapshotValidationError):
|
||||||
collect(client_with(response), "checko_licenses")
|
collect(client_with(response), "checko_licenses")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("source", ["checko_messages", "checko_leasing"])
|
||||||
|
def test_nullable_publisher_keeps_message_when_canonical_subject_is_participant(source):
|
||||||
|
first = fixture("messages-page-1.json")
|
||||||
|
first["data"]["Записи"][0]["Публикатор"] = None
|
||||||
|
rows = collect(client_with(first, fixture("messages-page-2.json")), source)
|
||||||
|
assert rows[0].payload["publisher_identifier"] is None
|
||||||
|
assert rows[0].payload["participant_identifiers"] == [ORG.inn]
|
||||||
|
assert rows[0].payload["upstream"]["Публикатор"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_nullable_publisher_does_not_admit_message_for_another_subject():
|
||||||
|
first = fixture("messages-page-1.json")
|
||||||
|
first["data"]["Записи"][0]["Публикатор"] = None
|
||||||
|
first["data"]["Записи"][0]["Участники"] = ["0000000000"]
|
||||||
|
with pytest.raises(
|
||||||
|
SnapshotValidationError, match="^checko_message_subject_mismatch$"
|
||||||
|
):
|
||||||
|
collect(client_with(first, fixture("messages-page-2.json")))
|
||||||
|
|||||||
@@ -105,7 +105,8 @@ def test_tls_trust_stays_default():
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path):
|
@pytest.mark.parametrize("trusted", [False, True])
|
||||||
|
def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path, trusted):
|
||||||
import hashlib
|
import hashlib
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
@@ -117,6 +118,9 @@ def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path):
|
|||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def response(session, url, **kwargs):
|
def response(session, url, **kwargs):
|
||||||
|
from apps.parsers.clients.common.structured import EIS_CA_BUNDLE_PATH
|
||||||
|
|
||||||
|
assert session.verify == (str(EIS_CA_BUNDLE_PATH) if trusted else True)
|
||||||
urls.append(url)
|
urls.append(url)
|
||||||
|
|
||||||
class Response:
|
class Response:
|
||||||
@@ -125,14 +129,16 @@ def test_download_checksum_date_private_file_and_three_bounded_reads(tmp_path):
|
|||||||
|
|
||||||
yield Response()
|
yield Response()
|
||||||
|
|
||||||
with override_settings(PARSER_PRIVATE_ARTIFACT_ROOT=str(tmp_path)), patch.object(
|
with override_settings(
|
||||||
module, "registry_response", response
|
PARSER_PRIVATE_ARTIFACT_ROOT=str(tmp_path),
|
||||||
):
|
EXCHANGE_SPB_RUSSIAN_TRUST_ENABLED=trusted,
|
||||||
|
), patch.object(module, "registry_response", response):
|
||||||
artifact = module.download_spb_artifact(load_batch=1)
|
artifact = module.download_spb_artifact(load_batch=1)
|
||||||
assert artifact.sha256 == hashlib.sha256(body).hexdigest()
|
assert artifact.sha256 == hashlib.sha256(body).hexdigest()
|
||||||
assert artifact.source_published_at.isoformat() == "2026-10-05"
|
assert artifact.source_published_at.isoformat() == "2026-10-05"
|
||||||
assert artifact.metadata["input_only"] is True
|
assert artifact.metadata["input_only"] is True
|
||||||
assert len(urls) == 3
|
assert len(urls) == 3
|
||||||
|
assert module.registry_session().verify is True
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
_ = artifact.file.url
|
_ = artifact.file.url
|
||||||
|
|
||||||
|
|||||||
@@ -995,7 +995,8 @@
|
|||||||
"nullable": true
|
"nullable": true
|
||||||
},
|
},
|
||||||
"publisher_identifier": {
|
"publisher_identifier": {
|
||||||
"type": "string"
|
"type": "string",
|
||||||
|
"nullable": true
|
||||||
},
|
},
|
||||||
"participant_identifiers": {
|
"participant_identifiers": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
@@ -1059,7 +1060,8 @@
|
|||||||
"nullable": true
|
"nullable": true
|
||||||
},
|
},
|
||||||
"publisher_identifier": {
|
"publisher_identifier": {
|
||||||
"type": "string"
|
"type": "string",
|
||||||
|
"nullable": true
|
||||||
},
|
},
|
||||||
"participant_identifiers": {
|
"participant_identifiers": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
|
|||||||
Reference in New Issue
Block a user