diff --git a/docs/source-data-export-api-spec.md b/docs/source-data-export-api-spec.md index dd65551..5110db2 100644 --- a/docs/source-data-export-api-spec.md +++ b/docs/source-data-export-api-spec.md @@ -10,6 +10,11 @@ observed_at: '2026-10-21' # Backend API страницы «Выгрузка данных из источников» +> Уточнение 2026-10-22: внутри каждого источника требуются отдельные годовые файлы. +> Правила partitioning, API v2 и включённого nightly schedule описаны в +> [актуальном дополнении](source-export-year-partitions.md); они имеют приоритет +> над прежними правилами datasets/parts ниже. + Назначение: самодостаточное задание backend-разработчику для подключения страницы `/admin/source-data-export`. Страница уже реализована на моках: каталог источников, раскрываемое описание и JSON-пример, отдельные части файлов, выбор формата у каждой части diff --git a/docs/source-export-catalog-operations.md b/docs/source-export-catalog-operations.md index 00bf497..eec6f89 100644 --- a/docs/source-export-catalog-operations.md +++ b/docs/source-export-catalog-operations.md @@ -4,7 +4,8 @@ опубликованные записи канонического хранилища всех 22 групп, включая финансовые строки прошлых лет. Legacy годовой API, `--all-years` и их storage не изменены. Фронтенд в эту реализацию не входит. -Фактические результаты локальных проверок: [QA report](source-export-catalog-verification.md). +Актуальные правила годовых файлов: [year partitions](source-export-year-partitions.md). +Фактические результаты локальных проверок: [QA report](source-export-year-partitions-verification.md). ## Подготовка контура @@ -21,12 +22,13 @@ синтетических данных не заменяют эту проверку. При необходимости сначала собрать одну группу. 4. Запустить сборку. Проверить `last_build`, counts, размеры, контрольные суммы, загрузку одного файла и ZIP через тот же origin `/api`, который использует браузер. -5. После проверки включить зарегистрированную миграцией **отключённую по умолчанию** задачу - Beat `organizations:source-export-catalog:nightly-msk` (06:30 Europe/Moscow, после annual). +5. Миграция `0021` включает Beat задачу `organizations:source-export-catalog:nightly-msk` + на 06:30 Europe/Moscow. До применения подготовить shared storage и capacity. `SOURCE_EXPORT_AUTOBUILD=true` дополнительно включает enqueue после публикации snapshot. При изменении данных во время сборки Celery повторяет сборку после завершения текущей. Без Beat использовать command в штатном таймере контура. + ```sh python src/manage.py build_source_export_catalog --source-group government_procurements python src/manage.py build_source_export_catalog @@ -37,7 +39,7 @@ python src/manage.py build_source_export_catalog --cleanup-only Команда продолжает остальные группы при ошибке одной и завершается ненулевым кодом, если хотя бы одна группа не обработана. Новый current публикуется транзакционно только после готовых checksums/manifest и atomic rename. Ошибка сохраняет старый current. -Сборка сортирует канонический snapshot по `(source,record_type,uid)` на локальном диске +Сборка сортирует канонический snapshot по `(year,source,record_type,uid)` на локальном диске SQLite с индексом вместо неограниченного RAM sort/PostgreSQL sort; financial lines упорядочены `(year,form_code,line_code,id)`. Финансы JSON-only; CSV/XLSX fallback в новом API нет. diff --git a/docs/source-export-catalog-verification.md b/docs/source-export-catalog-verification.md index bb55be1..0ba1d76 100644 --- a/docs/source-export-catalog-verification.md +++ b/docs/source-export-catalog-verification.md @@ -1,4 +1,7 @@ -# Проверка каталога all_available — 2026-10-22 +# Проверка первоначального каталога all_available — 2026-10-22 + +Это исторический отчёт для коммита `63872e8`. Последующее разбиение по годам +описано в [дополнении](source-export-year-partitions.md). Реализация backend в `dev`; frontend, реальные базы и серверы контуров не изменялись. [Операционная инструкция](source-export-catalog-operations.md), diff --git a/docs/source-export-year-partitions-verification.md b/docs/source-export-year-partitions-verification.md new file mode 100644 index 0000000..5bf34b7 --- /dev/null +++ b/docs/source-export-year-partitions-verification.md @@ -0,0 +1,43 @@ +# Проверка годовых файлов источников — 2026-10-22 + +[Правила и контракт](source-export-year-partitions.md). Изменения только в backend `dev`; +frontend и серверы контуров не изменялись. Первоначальный отчёт `63872e8` сохранён отдельно. + +| Проверка | Фактический результат | +| --- | --- | +| Полный backend pytest с transport load | 2086 passed, 48 skipped, 13 warnings | +| Итоговый каталог + конкурентный download/leases на PostgreSQL 15.19 | 42 passed | +| Full migration graph на PostgreSQL | PASS | +| 0021 forward/reverse/forward, enabled recurring schedule и Beat change counter | PASS | +| Migration drift / Django check / Ruff / Black / diff check | PASS | +| OpenAPI build + freshness, Orval apigen + TypeScript | PASS | +| Generated Zod: новые actual API responses | 5 passed | +| Generated Zod: прежние runtime responses | 48 passed | + +Полный прогон предшествовал окончательному scheduler notification guard; после него +итоговый каталог/миграция повторно проверены отдельным PostgreSQL прогоном. Skipped не PASS: +в основном SQLite-прогоне PostgreSQL-specific проверки пропускаются и выполняются отдельно. + +Проверены: + +- Все 22 источника: через ночной task entrypoint с синтетическими данными 2020/2021 годов + подготовлены 22 независимых поколения с обоими годами. Clock-trigger на реальном стенде + этой проверкой не подтверждается. +- В одном файле не смешиваются годы. Parts нумеруются внутри года; ZIP содержит папки годов. +- Разбиение oversized variant сохраняет тот же год и те же UID во всех CSV/XLSX/JSON. +- Финансовый UID с показателями двух лет присутствует в двух годовых проекциях, каждая + содержит только свои financial lines. Unique и projected counts не смешиваются. +- Пустая дата: год created_at в TIME_ZONE сервиса, независимо от активной timezone. + Нераспознаваемые даты/невалидный финансовый год не теряются и попадают в undated. +- JSON-only финансы, записи без financial lines, пустые источники, пагинация 51 части, + pinned tickets/старые manifest v3, ошибки хранилища, cleanup/leases и legacy annual API. +- Миграция включает recurring 06:30 Europe/Moscow, очищает one_off, expires/start_time + и частные args/kwargs; явно обновляет Beat change counter историческими migration models. + +Локальный transport test реально обработал 5905582210 bytes ZIP64, два +параллельных file reader по 536870912 bytes; peak RSS growth +11436032 bytes. Это synthetic transport/metadata, не HTTP proxy/browser +и не замер full-history объёма на dev. Ограничения эксплуатации в общей инструкции сохраняются. + +Временный PostgreSQL был изолированным локальным контейнером на loopback. Реальные миграции, +Beat, worker, private volume и первая сборка на dev-сервере требуют выкладки этой версии. diff --git a/docs/source-export-year-partitions.md b/docs/source-export-year-partitions.md new file mode 100644 index 0000000..5068edf --- /dev/null +++ b/docs/source-export-year-partitions.md @@ -0,0 +1,84 @@ +# Выгрузка каждого источника отдельными файлами по годам + +Уточнение пользователя от 2026-10-22 заменяет правило единого набора за все годы +в исходном [задании](source-data-export-api-spec.md). Фронтенд не изменяется. + +Ночная задача `organizations.tasks.refresh_source_export_catalog` обрабатывает весь +registry из 22 источников и все доступные годы их канонических опубликованных данных. +Миграция `0021_enable_yearly_partitioned_exports` включает recurring Beat schedule +`organizations:source-export-catalog:nightly-msk`: ежедневно **06:30 Europe/Moscow**. +Она также сбрасывает one_off и частные args/kwargs, чтобы задача запускала весь registry. +Источники, явно отключённые конфигурацией `SOURCE_EXPORT_DISABLED_GROUPS`, сохраняют свой +статус disabled; по умолчанию отключённых нет. Источник без данных публикует empty manifest, +а не фиктивные файлы. Регистрация расписания в коде не доказывает его запуск на сервере: +для этого нужны выкладка, migrate, общий private volume, работающие worker и Beat. + +## Определение года и полнота + +- Для обычной записи год — первая самостоятельная последовательность из четырёх цифр + в `record_date` (1..9999). Поддерживаются, например, + `2024-12-31` и `31.12.2024`. +- Если `record_date` пустая, используется год `created_at` в `TIME_ZONE` сервиса. +- Непустая дата без распознаваемого года сохраняется в `undated`, metadata `year: null`. + Она не получает вымышленный год и не пропадает из выгрузки. +- У финансов год определяется каждой строкой `financial_lines.year`. В годовую проекцию + исходной записи входят только финансовые строки этого года. Один исходный UID может + законно присутствовать в нескольких годах. Финансовая запись без строк сохраняется по + общему правилу даты; неподдерживаемые значения года финансовых строк попадают в undated. +- Нет ограничения текущим годом. Полный snapshot источника читается один раз; сортировка + на диске — `(year partition, source, record_type, uid)`. Все годы публикуются атомарно + одним неизменяемым generation источника. Ошибка любого года сохраняет прежний current. + +## Файлы и API + +Например, ZIP закупок содержит: + +```text +2024/public-procurements-2024-part-000001.xlsx +2024/public-procurements-2024-part-000002.xlsx +2025/public-procurements-2025-part-000001.xlsx +undated/public-procurements-undated-part-000001.xlsx +manifest.json +``` + +Один ZIP источника включает **все годы и все части** выбранного формата, независимо от +страницы metadata. Отдельная кнопка файла сохраняет только одну выбранную годовую часть. +Финансы остаются JSON-only. Лимиты размера, одинаковые записи во всех variants части, +checksums, защищённые tickets, retention и leases сохраняются. + +Public catalog `schema_version: "2"`, внутренний manifest `version: 4`. +`data_scope` по-прежнему `all_available` — охватывает все доступные годы. + +| Поле | Семантика | +| --- | --- | +| summary/detail `partitioning` | `year`; для сохранённых прежних generation — `none` | +| dataset `key` | `records_2024`, `records_2025`, `records_undated` | +| dataset/part `year` | Числовой год; null у undated и прежних generation без разбиения | +| dataset `export_schema_version` | `"2"`, годовая файловая проекция | +| part `part_number`, `parts_count` | Нумерация и количество частей **внутри года/dataset** | +| source `records_count` | Уникальные исходные записи источника | +| source `exported_records_count` | Сумма годовых проекций; может быть больше unique count финансов | +| dataset/part `records_count` | Только записи этого dataset/этой части; не сумма variants | + +Порядок страниц `(dataset_key, part_number)`, форматы и части каждого года согласованы. +Description example ссылается на фактический годовой dataset. Недатированные записи имеют +отдельный dataset и находятся в конце списка. Пустые годы не создаются искусственно. + +Сохранённые manifest v3, их metadata и выданные tickets остаются читаемыми; bytes старого +поколения не заменяются годовой выгрузкой. У старых parts/datasets API возвращает year=null. +Legacy synchronous annual export и его задачи/storage не изменены. + +## Проверка и запуск + +Команда и Celery entrypoint прежние — теперь они автоматически готовят годовые части: + +```sh +python src/manage.py migrate --noinput +python src/manage.py build_source_export_catalog +python src/manage.py build_source_export_catalog --verify-only +``` + +В dev Compose команды сборки/cleanup выполнять в worker: web имеет read-only mount +private artifacts. [Общая эксплуатация](source-export-catalog-operations.md). + +Результаты проверок: [годовой QA report](source-export-year-partitions-verification.md). diff --git a/src/core/openapi.json b/src/core/openapi.json index a7a9de0..1f92645 100644 --- a/src/core/openapi.json +++ b/src/core/openapi.json @@ -25400,6 +25400,13 @@ "all_available" ] }, + "partitioning": { + "type": "string", + "enum": [ + "year", + "none" + ] + }, "source_slug": { "type": "string" }, @@ -25420,6 +25427,12 @@ "maximum": 9007199254740991, "nullable": true }, + "exported_records_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "nullable": true + }, "parts_count": { "type": "integer", "minimum": 0, @@ -25462,11 +25475,13 @@ "generated_at", "data_as_of", "data_scope", + "partitioning", "source_slug", "title", "order", "export_enabled", "records_count", + "exported_records_count", "parts_count", "supported_formats", "default_format", @@ -25491,7 +25506,7 @@ "schema_version": { "type": "string", "enum": [ - "1" + "2" ] }, "catalog_revision": { @@ -25574,6 +25589,12 @@ "key": { "type": "string" }, + "year": { + "type": "integer", + "minimum": 1, + "maximum": 9999, + "nullable": true + }, "title": { "type": "string" }, @@ -25593,6 +25614,7 @@ }, "required": [ "key", + "year", "title", "export_schema_version", "records_count", @@ -25649,6 +25671,12 @@ "type": "string", "format": "uuid" }, + "year": { + "type": "integer", + "minimum": 1, + "maximum": 9999, + "nullable": true + }, "dataset_key": { "type": "string" }, @@ -25688,6 +25716,7 @@ }, "required": [ "part_id", + "year", "dataset_key", "title", "part_number", @@ -25809,6 +25838,13 @@ "all_available" ] }, + "partitioning": { + "type": "string", + "enum": [ + "year", + "none" + ] + }, "current_generation_id": { "type": "string", "format": "uuid", @@ -25838,6 +25874,7 @@ "generated_at", "data_as_of", "data_scope", + "partitioning", "current_generation_id", "description", "datasets", diff --git a/src/organizations/management/commands/build_source_export_catalog.py b/src/organizations/management/commands/build_source_export_catalog.py index b5bd3e3..f91ded9 100644 --- a/src/organizations/management/commands/build_source_export_catalog.py +++ b/src/organizations/management/commands/build_source_export_catalog.py @@ -1,4 +1,4 @@ -"""Prepare new all-available export generations without changing annual exports.""" +"""Prepare source exports partitioned by year without changing legacy annual exports.""" from django.core.management.base import BaseCommand, CommandError from organizations.models import SourceExportGeneration @@ -11,7 +11,7 @@ from organizations.source_export_catalog import ( class Command(BaseCommand): - help = "Собрать all_available каталог и файлы существующих источников" + help = "Собрать файлы всех источников по доступным годам" def add_arguments(self, parser): parser.add_argument("--source-group", choices=list(registry())) diff --git a/src/organizations/migrations/0021_enable_yearly_partitioned_exports.py b/src/organizations/migrations/0021_enable_yearly_partitioned_exports.py new file mode 100644 index 0000000..1473cc5 --- /dev/null +++ b/src/organizations/migrations/0021_enable_yearly_partitioned_exports.py @@ -0,0 +1,56 @@ +"""Enable nightly preparation of all sources partitioned by calendar year.""" +from django.db import migrations +from django.utils import timezone + +NAME = "organizations:source-export-catalog:nightly-msk" + + +def schedule_changed(apps): + # Historical migration models do not run PeriodicTask's save/signals. + apps.get_model("django_celery_beat", "PeriodicTasks").objects.update_or_create( + ident=1, defaults={"last_update": timezone.now()} + ) + + +def enable(apps, schema_editor): + Cron = apps.get_model("django_celery_beat", "CrontabSchedule") + Task = apps.get_model("django_celery_beat", "PeriodicTask") + cron, _ = Cron.objects.get_or_create( + minute="30", + hour="6", + day_of_week="*", + day_of_month="*", + month_of_year="*", + timezone="Europe/Moscow", + ) + Task.objects.update_or_create( + name=NAME, + defaults={ + "task": "organizations.tasks.refresh_source_export_catalog", + "enabled": True, + "one_off": False, + "expires": None, + "expire_seconds": None, + "start_time": None, + "args": "[]", + "kwargs": "{}", + "crontab": cron, + "interval": None, + "solar": None, + "clocked": None, + "description": "Nightly preparation of all 22 sources, with separate files for every available calendar year.", + }, + ) + schedule_changed(apps) + + +def disable(apps, schema_editor): + apps.get_model("django_celery_beat", "PeriodicTask").objects.filter( + name=NAME + ).update(enabled=False) + schedule_changed(apps) + + +class Migration(migrations.Migration): + dependencies = [("organizations", "0020_source_export_catalog_schedule")] + operations = [migrations.RunPython(enable, reverse_code=disable)] diff --git a/src/organizations/source_export_catalog.py b/src/organizations/source_export_catalog.py index 04366bb..8d3f78f 100644 --- a/src/organizations/source_export_catalog.py +++ b/src/organizations/source_export_catalog.py @@ -217,6 +217,12 @@ def summary(entry, state=None, generation=None, revision=None): "data_as_of": manifest["data_as_of"] if manifest else None, "data_scope": "all_available", "records_count": manifest["records_count"] if manifest else None, + "exported_records_count": manifest.get( + "exported_records_count", manifest["records_count"] + ) + if manifest + else None, + "partitioning": manifest.get("partitioning", "none") if manifest else "year", "parts_count": len(manifest["parts"]) if manifest else None, "supported_formats": formats, "default_format": formats[0] if formats else None, @@ -251,7 +257,7 @@ def catalog(): # is_stale may change solely with age; revision tracks actual persisted metadata. persisted = [{k: v for k, v in item.items() if k != "is_stale"} for item in sources] return { - "schema_version": "1", + "schema_version": "2", "catalog_revision": hashlib.sha256(_json_bytes(persisted)).hexdigest(), "sources": sources, } @@ -309,6 +315,7 @@ def detail(group, query): "generated_at", "data_as_of", "data_scope", + "partitioning", ) } data.update( @@ -317,8 +324,13 @@ def detail(group, query): if state and state.current_generation else None, "description": manifest.get("description", _description(entry)), - "datasets": manifest.get("datasets", []), - "files": parts[(page - 1) * size : page * size], + "datasets": [ + {"year": None, **dataset} for dataset in manifest.get("datasets", []) + ], + "files": [ + {"year": None, **part} + for part in parts[(page - 1) * size : page * size] + ], } ) return data, { @@ -331,7 +343,7 @@ def detail(group, query): } -def _description(entry, example=None): +def _description(entry, example=None, example_key="records"): return { "composition": entry["composition"], "origin": entry["origin"], @@ -342,7 +354,7 @@ def _description(entry, example=None): "предметные поля источника", ] ), - "example_dataset_key": "records" if example else None, + "example_dataset_key": example_key if example else None, "example_is_synthetic": False, "example_record": example, } @@ -417,6 +429,32 @@ def _build_lock(group): _build_state(group, owner, lock_owner=None, lock_expires_at=None) +def _record_year(record): + """Use the canonical record-date year; missing dates use the ingestion year.""" + if not record.record_date: + return timezone.localtime( + record.created_at, timezone.get_default_timezone() + ).year + match = re.search(r"(?= max_rows or batch_bytes + size > target - ): - output.close() - parts.extend( - _render_part( - group, - part_spool, - staging, - headers, - batch_count, - formats, - len(parts) + 1, - ) + for row in annual_rows: + line = _json_bytes(row).decode("utf-8") + "\n" + size = len(line.encode("utf-8")) + if batch_count and (batch_count >= max_rows or batch_bytes + size > target): + output.close() + parts.extend( + _render_part( + group, + part_spool, + staging, + headers, + batch_count, + formats, + len(parts) + 1, + year, ) - output = part_spool.open("w", encoding="utf-8") - batch_count, batch_bytes = 0, 0 - output.write(line) - batch_count += 1 - batch_bytes += size + ) + output = part_spool.open("w", encoding="utf-8") + batch_count, batch_bytes = 0, 0 + output.write(line) + batch_count += 1 + batch_bytes += size output.close() if batch_count: parts.extend( @@ -640,6 +693,7 @@ def _render_parts(group, staging, spool, headers, formats): batch_count, formats, len(parts) + 1, + year, ) ) finally: @@ -648,6 +702,51 @@ def _render_parts(group, staging, spool, headers, formats): return parts +def _render_parts(group, staging, spool, headers, formats): + from itertools import groupby + + parts = [] + with spool.open(encoding="utf-8") as source: + envelopes = (json.loads(line) for line in source) + for year, rows in groupby(envelopes, key=lambda item: item["year"]): + annual = _render_year_parts( + group, staging, (item["row"] for item in rows), headers, formats, year + ) + title = _entry(group)["title"] + ( + f" — {year:04d} год" if year else " — год не определён" + ) + for part in annual: + part["parts_count"] = len(annual) + part["title"] = title + ( + f" — часть {part['part_number']} из {len(annual)}" + if len(annual) > 1 + else "" + ) + parts.extend(annual) + return parts + + +def _annual_datasets(parts, title): + from itertools import groupby + + datasets = [] + for key, grouped in groupby(parts, key=lambda p: p["dataset_key"]): + rows = list(grouped) + year = rows[0]["year"] + datasets.append( + { + "key": key, + "year": year, + "title": title + + (f" — {year:04d} год" if year else " — год не определён"), + "export_schema_version": "2", + "records_count": sum(p["records_count"] for p in rows), + "parts_count": len(rows), + } + ) + return datasets + + def build_source(group): entry = _entry(group) if not entry["export_enabled"]: @@ -665,20 +764,15 @@ def build_source(group): raise OSError("Export disk reserve exhausted") staging.mkdir(mode=0o700) spool = staging / ".rows.jsonl" - headers, count, example, as_of, revision = _spool(group, spool) + headers, count, example, as_of, revision, example_key = _spool(group, spool) formats = ("json",) if group == FINANCIAL_SOURCE_GROUP else FORMATS parts = _render_parts(group, staging, spool, headers, formats) spool.unlink() - for part in parts: - part["parts_count"] = len(parts) - part["title"] = entry["title"] + ( - f" — часть {part['part_number']} из {len(parts)}" - if len(parts) > 1 - else "" - ) _check_capacity(staging) manifest = { - "version": 3, + "version": 4, + "partitioning": "year", + "exported_records_count": sum(p["records_count"] for p in parts), "data_scope": "all_available", "source_group": group, "generation_id": str(uid), @@ -686,16 +780,8 @@ def build_source(group): "data_as_of": as_of, "records_count": count, "supported_formats": list(formats) if count else [], - "description": _description(entry, example), - "datasets": [ - { - "key": "records", - "title": entry["title"], - "export_schema_version": "1", - "records_count": count, - "parts_count": len(parts), - } - ], + "description": _description(entry, example, example_key), + "datasets": _annual_datasets(parts, entry["title"]), "parts": parts, } (staging / "manifest.json").write_bytes(_json_bytes(manifest)) @@ -915,7 +1001,9 @@ def _stream_zip(opened, manifest): ) as archive: for artifact, handle in opened: with archive.open( - "records/" + artifact["file_name"], "w", force_zip64=True + artifact.get("archive_path", "records/" + artifact["file_name"]), + "w", + force_zip64=True, ) as target: yield from sink.drain() transferred = 0 @@ -1092,6 +1180,24 @@ def _admission_error(generation, lease, now): def _prepare_stream(generation, lease, payload, stack, now): opened = _open_artifacts(generation, payload["artifacts"], stack) + if generation.manifest.get("partitioning") == "year": + years = { + v["artifact_id"]: f"{p['year']:04d}" if p["year"] else "undated" + for p in generation.manifest["parts"] + for v in p["variants"] + } + opened = [ + ( + { + **artifact, + "archive_path": years[artifact["artifact_id"]] + + "/" + + artifact["file_name"], + }, + handle, + ) + for artifact, handle in opened + ] lease.kind, lease.expires_at = "stream", now + timedelta(minutes=10) lease.save(update_fields=["kind", "expires_at"]) manifest = { diff --git a/src/organizations/tasks.py b/src/organizations/tasks.py index 7bbae28..7683844 100644 --- a/src/organizations/tasks.py +++ b/src/organizations/tasks.py @@ -128,7 +128,7 @@ def refresh_organization_data_snapshots_for_parser_batch( @shared_task(bind=True, base=CorePeriodicTask) def refresh_source_export_catalog(self, source_group=None): - """Independent group publication; contention retries the latest canonical data.""" + """Build all sources by year; independently publish each complete group.""" from organizations.source_export_catalog import ( ExportError, build_source, diff --git a/tests/apps/organizations/test_source_export_catalog.py b/tests/apps/organizations/test_source_export_catalog.py index 70cd8dd..9b84733 100644 --- a/tests/apps/organizations/test_source_export_catalog.py +++ b/tests/apps/organizations/test_source_export_catalog.py @@ -369,8 +369,20 @@ class SourceExportCatalogTest(APITestCase): rows = json.loads(self.bytes(consume_ticket(ticket["ticket"]))) self.assertEqual( [r["year"] for r in rows[0]["financial_indicators"][0]["financial_lines"]], - [2022, 2023], + [2022], ) + self.assertEqual(generation.manifest["records_count"], 1) + self.assertEqual(generation.manifest["exported_records_count"], 2) + self.assertEqual( + [d["year"] for d in generation.manifest["datasets"]], [2022, 2023] + ) + for part in generation.manifest["parts"]: + variant = part["variants"][0] + projected = json.loads( + (_directory(generation) / variant["file_name"]).read_bytes() + ) + lines = projected[0]["financial_indicators"][0]["financial_lines"] + self.assertEqual({line["year"] for line in lines}, {part["year"]}) with self.assertRaises(ExportError) as error: issue_ticket(self.user, self.selector(generation, fmt="xlsx")) self.assertEqual(error.exception.status, 409) @@ -394,14 +406,17 @@ class SourceExportCatalogTest(APITestCase): import secrets for record in self.records(5): + record.record_date = "2024-01-01" record.payload = {"text": secrets.token_hex(1200)} - record.save(update_fields=["payload"]) + record.save(update_fields=["payload", "record_date"]) with override_settings( SOURCE_EXPORT_ROWS_PER_PART=100, SOURCE_EXPORT_MAX_FILE_BYTES=10000 ): generation = build_source(GROUP) self.assertGreater(len(generation.manifest["parts"]), 1) for part in generation.manifest["parts"]: + self.assertEqual(part["year"], 2024) + self.assertEqual(part["dataset_key"], "records_2024") self.assertTrue(all(v["size_bytes"] <= 10000 for v in part["variants"])) self.assertEqual( sum(p["records_count"] for p in generation.manifest["parts"]), 5 @@ -681,3 +696,228 @@ class SourceExportCatalogTest(APITestCase): self.base + "export-ticket/", "{bad", content_type="application/json" ) self.assertEqual(response.status_code, 401) + + def test_year_boundaries_dates_and_undated_do_not_mix(self): + from datetime import UTC, datetime + + records = self.records(5) + values = ["2021-12-31", "01.01.2022", "", "неизвестно", "16599930000"] + for record, value in zip(records, values, strict=True): + OrganizationSourceRecord.objects.filter(pk=record.pk).update( + record_date=value, created_at=datetime(2023, 12, 31, 22, 0, tzinfo=UTC) + ) + with override_settings( + TIME_ZONE="Europe/Moscow", SOURCE_EXPORT_ROWS_PER_PART=1 + ), timezone.override("Pacific/Honolulu"): + generation = build_source(GROUP) + by_year = {} + for part in generation.manifest["parts"]: + variant = next(v for v in part["variants"] if v["format"] == "json") + rows = json.loads( + (_directory(generation) / variant["file_name"]).read_bytes() + ) + by_year.setdefault(part["year"], set()).update( + r["uid"] for org in rows for r in org[GROUP] + ) + self.assertEqual( + by_year, + { + 2021: {str(records[0].uid)}, + 2022: {str(records[1].uid)}, + 2024: {str(records[2].uid)}, + None: {str(records[3].uid), str(records[4].uid)}, + }, + ) + self.assertEqual(generation.manifest["exported_records_count"], 5) + self.assertEqual( + [d["year"] for d in generation.manifest["datasets"]], + [2021, 2022, 2024, None], + ) + + def test_year_parts_numbers_formats_and_zip_directories(self): + records = self.records(7) + generation = build_source(GROUP) + self.assertEqual( + [d["records_count"] for d in generation.manifest["datasets"]], [3, 2, 2] + ) + self.assertEqual( + [p["part_number"] for p in generation.manifest["parts"]], [1, 2, 1, 1] + ) + for part in generation.manifest["parts"]: + for variant in part["variants"]: + self.assertIn(f'-{part["year"]}-part-', variant["file_name"]) + variant = next(v for v in part["variants"] if v["format"] == "json") + rows = json.loads( + (_directory(generation) / variant["file_name"]).read_bytes() + ) + projected = [r for org in rows for r in org[GROUP]] + self.assertEqual( + {int(r["record_date"][:4]) for r in projected}, {part["year"]} + ) + ticket = issue_ticket( + self.user, self.selector(generation, "source_archive", "json") + ) + with zipfile.ZipFile( + BytesIO(self.bytes(consume_ticket(ticket["ticket"]))) + ) as archive: + self.assertEqual( + {n.split("/")[0] for n in archive.namelist() if n != "manifest.json"}, + {"2024", "2025", "2026"}, + ) + self.assertEqual(len(archive.namelist()), 5) + manifest = json.loads(archive.read("manifest.json")) + self.assertEqual(manifest["partitioning"], "year") + self.assertEqual(manifest["records_count"], len(records)) + + def test_financial_record_without_lines_and_invalid_line_year_are_retained(self): + extension = FinancialIndicatorsExtension.objects.create( + organization=self.organization + ) + empty = OrganizationSourceRecord.objects.create( + extension=extension, + source="fns_reports", + record_type="financial_report", + external_id=str(uuid4()), + record_date="2019-01-01", + ) + invalid = OrganizationSourceRecord.objects.create( + extension=extension, + source="fns_reports", + record_type="financial_report", + external_id=str(uuid4()), + ) + OrganizationSourceFinancialLine.objects.create( + source_record=invalid, year=0, form_code="1", line_code="1" + ) + generation = build_source("financial_indicators") + self.assertEqual( + [d["year"] for d in generation.manifest["datasets"]], [2019, None] + ) + self.assertEqual(generation.manifest["records_count"], 2) + self.assertEqual(generation.manifest["exported_records_count"], 2) + rows = [] + for part in generation.manifest["parts"]: + variant = part["variants"][0] + rows.extend( + r + for org in json.loads( + (_directory(generation) / variant["file_name"]).read_bytes() + ) + for r in org["financial_indicators"] + ) + self.assertEqual({r["uid"] for r in rows}, {str(empty.uid), str(invalid.uid)}) + + def test_pre_partition_generation_metadata_and_ticket_stay_readable(self): + self.records(1) + generation = build_source(GROUP) + manifest = generation.manifest + manifest["version"] = 3 + manifest["description"]["example_dataset_key"] = "records" + manifest.pop("partitioning") + manifest.pop("exported_records_count") + for part in manifest["parts"]: + part.pop("year") + part["dataset_key"] = "records" + for dataset in manifest["datasets"]: + dataset.pop("year") + dataset["key"] = "records" + dataset["export_schema_version"] = "1" + generation.save(update_fields=["manifest"]) + ticket = issue_ticket(self.user, self.selector(generation)) + expected = (_directory(generation) / ticket["file_name"]).read_bytes() + build_source(GROUP) + data, _ = detail(GROUP, QueryDict(f"generation_id={generation.pk}")) + self.assertEqual(data["partitioning"], "none") + self.assertIsNone(data["files"][0]["year"]) + self.assertIsNone(data["datasets"][0]["year"]) + self.assertEqual(self.bytes(consume_ticket(ticket["ticket"])), expected) + + def test_nightly_dispatch_builds_twenty_two_sources_for_both_years(self): + from organizations.source_groups import SOURCE_GROUP_DESCRIPTORS + from organizations.tasks import refresh_source_export_catalog + + for group in registry(): + descriptor = next( + d for d in SOURCE_GROUP_DESCRIPTORS.values() if d.source_group == group + ) + extension = descriptor.extension_model.objects.filter( + organization=self.organization + ).first() or descriptor.extension_model.objects.create( + organization=self.organization + ) + for year in [2020, 2021]: + record = OrganizationSourceRecord.objects.create( + extension=extension, + source=descriptor.source, + record_type=descriptor.record_type, + external_id=str(uuid4()), + record_date=f"{year}-01-01", + ) + if group == "financial_indicators": + OrganizationSourceFinancialLine.objects.create( + source_record=record, year=year, form_code="1", line_code="1" + ) + with patch.object( + refresh_source_export_catalog, + "delay", + side_effect=lambda **kw: refresh_source_export_catalog.run(**kw), + ): + result = refresh_source_export_catalog.run() + self.assertEqual(result["groups"], 22) + self.assertEqual(SourceExportGeneration.objects.count(), 22) + for generation in SourceExportGeneration.objects.all(): + self.assertEqual(generation.manifest["partitioning"], "year") + self.assertEqual( + [d["year"] for d in generation.manifest["datasets"]], [2020, 2021] + ) + self.assertEqual(generation.manifest["records_count"], 2) + + def test_nightly_migration_enables_recurring_all_sources_schedule(self): + from importlib import import_module + + from django.apps import apps + from django_celery_beat.models import PeriodicTask + + migration = import_module( + "organizations.migrations.0021_enable_yearly_partitioned_exports" + ) + migration.enable(apps, None) + task = PeriodicTask.objects.get(name=migration.NAME) + self.assertTrue(task.enabled) + self.assertFalse(task.one_off) + self.assertEqual(task.kwargs, "{}") + self.assertEqual(task.crontab.hour, "6") + self.assertEqual(task.crontab.minute, "30") + self.assertEqual(str(task.crontab.timezone), "Europe/Moscow") + task.one_off = True + task.expires = timezone.now() - timedelta(days=1) + task.start_time = timezone.now() + timedelta(days=10) + task.kwargs = '{"source_group":"arbitration"}' + task.save() + migration.enable(apps, None) + task.refresh_from_db() + self.assertFalse(task.one_off) + self.assertIsNone(task.expires) + self.assertIsNone(task.expire_seconds) + self.assertIsNone(task.start_time) + self.assertEqual(task.kwargs, "{}") + self.assertEqual(PeriodicTask.objects.filter(name=migration.NAME).count(), 1) + + def test_nightly_migration_notifies_beat_without_live_model_signals(self): + from importlib import import_module + + from django.apps import apps + from django_celery_beat.models import PeriodicTasks + + migration = import_module( + "organizations.migrations.0021_enable_yearly_partitioned_exports" + ) + # Historical migration models do not execute the live save hooks. + with patch.object(PeriodicTasks, "update_changed"): + PeriodicTasks.objects.all().delete() + migration.enable(apps, None) + self.assertTrue(PeriodicTasks.objects.filter(ident=1).exists()) + old = timezone.now() - timedelta(days=30) + PeriodicTasks.objects.filter(ident=1).update(last_update=old) + migration.disable(apps, None) + self.assertGreater(PeriodicTasks.objects.get(ident=1).last_update, old) diff --git a/tools/openapi/contract.ts b/tools/openapi/contract.ts index 265f985..6ebe0e9 100644 --- a/tools/openapi/contract.ts +++ b/tools/openapi/contract.ts @@ -57,3 +57,11 @@ export async function exportSelection(selector: SourceExportFileTicketRequest | } return ''; } + +import type { SourceExportPart, SourceExportSourceSummary } from './generated/schemas'; +export function sourceExportYear(part: SourceExportPart, source: SourceExportSourceSummary): string { + const year: number | null = part.year; + const partitioning: 'year' | 'none' = source.partitioning; + const projections: number | null = source.exported_records_count; + return `${partitioning}:${year ?? 'undated'}:${projections}`; +} diff --git a/tools/openapi/source-export-catalog.mjs b/tools/openapi/source-export-catalog.mjs index 716d143..a3698f1 100644 --- a/tools/openapi/source-export-catalog.mjs +++ b/tools/openapi/source-export-catalog.mjs @@ -7,6 +7,7 @@ export function addSourceExportCatalog(document) { const date = { type: 'string', format: 'date-time' }; const integer = { type: 'integer', minimum: 0, maximum: 9007199254740991 }; const positive = { ...integer, minimum: 1 }; + const year = { type: 'integer', minimum: 1, maximum: 9999, nullable: true }; const bool = { type: 'boolean' }; const enumeration = values => ({ type: 'string', enum: values }); const format = enumeration(['xlsx', 'csv', 'json']); @@ -20,19 +21,19 @@ export function addSourceExportCatalog(document) { source_group: group, generation_id: nullable(uuid), state: enumeration(['ready', 'empty', 'not_ready', 'building', 'unavailable']), unavailable_reason: nullable(enumeration(['disabled', 'adapter_missing', 'build_failed', 'storage_unavailable'])), - generated_at: nullable(date), data_as_of: nullable(date), data_scope: enumeration(['all_available']), + generated_at: nullable(date), data_as_of: nullable(date), data_scope: enumeration(['all_available']), partitioning: enumeration(['year', 'none']), }; schemas.SourceExportSourceSummary = object({ ...snapshot, source_slug: string, title: string, order: integer, export_enabled: bool, - records_count: nullable(integer), parts_count: nullable(integer), supported_formats: { ...array(format), uniqueItems: true }, + records_count: nullable(integer), exported_records_count: nullable(integer), parts_count: nullable(integer), supported_formats: { ...array(format), uniqueItems: true }, default_format: nullable(format), is_stale: bool, last_build: ref('SourceExportBuildSummary') }); const envelope = (data, meta = nil) => object({ success: { type: 'boolean', enum: [true] }, data, errors: nil, meta }); - schemas.SourceExportCatalogResponse = envelope(object({ schema_version: enumeration(['1']), catalog_revision: string, sources: array(ref('SourceExportSourceSummary')) })); + schemas.SourceExportCatalogResponse = envelope(object({ schema_version: enumeration(['2']), catalog_revision: string, sources: array(ref('SourceExportSourceSummary')) })); schemas.SourceExportDescription = object({ composition: string, origin: string, fields: string, example_dataset_key: nullable(string), example_is_synthetic: bool, example_record: { type: 'object', additionalProperties: true, nullable: true } }); - schemas.SourceExportDataset = object({ key: string, title: string, export_schema_version: string, records_count: integer, parts_count: integer }); + schemas.SourceExportDataset = object({ key: string, year, title: string, export_schema_version: string, records_count: integer, parts_count: integer }); schemas.SourceExportArtifact = object({ artifact_id: uuid, format, file_name: { type: 'string', pattern: '^[A-Za-z0-9._-]+$' }, mime_type: string, size_bytes: positive, sha256: { type: 'string', pattern: '^[0-9a-f]{64}$' } }); - schemas.SourceExportPart = object({ part_id: uuid, dataset_key: string, title: string, part_number: positive, parts_count: positive, records_count: positive, + schemas.SourceExportPart = object({ part_id: uuid, year, dataset_key: string, title: string, part_number: positive, parts_count: positive, records_count: positive, default_format: format, variants: { ...array(ref('SourceExportArtifact')), minItems: 1 } }); schemas.SourceExportPagination = object({ page: positive, page_size: { ...positive, maximum: 200 }, total_count: integer, total_pages: positive, has_next: bool, has_previous: bool }); schemas.SourceExportSourceDetail = object({ ...snapshot, current_generation_id: nullable(uuid), description: ref('SourceExportDescription'), datasets: array(ref('SourceExportDataset')), files: array(ref('SourceExportPart')) });