Files
ss-tools/specs/028-llm-datasource-supeset/effort-estimate-report.md
busya ec6421de35 rename ss-tools to superset-tools across the entire project
- Replace all occurrences of 'ss-tools' with 'superset-tools' in 104 files
- Rename git bundle file ss-tools.bundle → superset-tools.bundle
- Update .gitignore pattern accordingly
- Preserve variable names (hasSsTools etc.) and code identifiers
2026-06-16 11:15:19 +03:00

721 lines
47 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Отчёт об оценке трудозатрат: Feature 028 — LLM Table Translation Service
**Дата**: 2026-05-18 (актуализация: 2026-06-16)
**Ветка**: `master`
**Автор**: Speckit Workflow Specialist
---
## Сводка
Feature 028 реализован полностью (core: ~153 файла, ~36 091 строка кода, **7778 pytest** (98.4% real coverage), ~70 vitest).
**Enhancement Phase** (Direct DB Insert + Connection Settings, US11US12): в активной разработке — ~21 новых файлов, ~3 301 строка кода, ~16 новых тестовых файлов.
> **2026-06-16: Кампания по покрытию тестами.** Покрытие backend unit-тестами поднято с 48% до **98.4%** (реальное, исключая `__tests__/`). Количество тестов выросло с ~1723 до **7778** (+6055). Кампания заняла ~4 сессии (80+ agent-steps), задействовала ~25 параллельных python-coder/fullstack-coder агентов. Основные достижения: все модули `core/` → 95-100%, `services/` → 94-100%, `api/routes/` → 95-100%, `plugins/translate/` → 85-98%, `schemas/` + `models/` → 99-100%. Создано ~120 новых тестовых файлов, исправлены критические проблемы тестовой pollution (sys.modules). См. ADR-0013 и `docs/orthogonal-test-report.md`.
Настоящий отчёт оценивает трудозатраты **ретроспективно** — как если бы фичу нужно было реализовать заново в трёх сценариях:
| Сценарий | Человеко-месяцев | Человеко-дней (1 dev) | Риски |
|----------|:-:|:-:|-------|
| **A. Standalone (с нуля, без superset-tools)** | 7.59.5 | 165209 | Высокие: инфраструктура с нуля |
| **B. В рамках superset-tools (core)** | 2.53 | 5566 | Низкие: переиспользование отлаженных компонентов |
| **C. В рамках superset-tools (core + enhancement)** | 3.03.5 | 6677 | Низкие: ~1011 дополнительных дней на US11US12 |
| **Экономия superset-tools** | **~6265%** | — | — |
---
## Методология оценки
Оценка основана на:
1. **Фактическом объёме кода**: 148+21=169 файлов, ~39 392 строк (подтверждено `wc -l`)
2. **Статистике дефектов/тестов**: **7778 pytest** (98.4% real coverage) + ~70 vitest
3. **Сложности модулей**: 2× C5, 6× C4, 12× C3, 7× C2, 4× C1 (core) + 2× C3, 2× C2, 2× C1 (enhancement)
4. **Анализе переиспользования**: 7 интеграционных контрактов с существующей инфраструктурой superset-tools
5. **Метриках из смежных проектов**: базовая производительность 50100 строк/день для C4+ с учётом тестов
**Норматив**: 3050 строк кода в день на C4+ модули (с учётом тестов, документирования, семантических контрактов, ревью), 80120 строк/день для C1C2.
---
## 1. Сценарий A: Standalone-реализация
### Что нужно построить с нуля
Feature 028 — это полноценный full-stack web-сервис. В standalone-сценарии вся инфраструктура пишется с нуля:
#### 1.1 Инфраструктура бэкенда
| Компонент | Аналог в superset-tools | Строк кода | Трудозатраты (дней) |
|-----------|-------------------|:-:|:-:|
| FastAPI-приложение (app, middleware, CORS, lifespan) | `backend/src/app.py` | ~600 | 5 |
| Система аутентификации (JWT, пароли, сессии) | `backend/src/auth/` | ~2 500 | 20 |
| RBAC (роли, permissions, проверки в DI) | `backend/src/services/rbac_permission_catalog.py` | ~1 500 | 12 |
| SQLAlchemy Base, engine, session factory, миграции Alembic | `backend/src/core/database.py` | ~400 | 3 |
| Plugin system (PluginBase, PluginLoader, авто-дискавери) | `backend/src/core/plugin_base.py` | ~800 | 6 |
| Superset API client (datasources, datasets, SQL Lab) | `backend/src/core/superset_client/` | ~3 500 | 25 |
| LLM provider management (CRUD, шифрование ключей, OpenAI-клиент) | `backend/src/services/llm_provider.py` | ~1 200 | 10 |
| APScheduler integration + SchedulerService | `backend/src/core/scheduler.py` | ~600 | 5 |
| WebSocket infrastructure + TaskManager | `backend/src/core/ws_log_handler.py`, `task_manager/` | ~1 200 | 10 |
| NotificationService (SMTP, Telegram, Slack) | `backend/src/services/notifications/` | ~800 | 6 |
| Event logging / audit trail система | `events.py` паттерны | ~500 | 4 |
| Retention/pruning утилиты | `events.prune_expired()` | ~300 | 3 |
| **Subtotal infrastructure** | | **~13 900** | **109** |
#### 1.2 Инфраструктура фронтенда
| Компонент | Аналог в superset-tools | Строк кода | Трудозатраты (дней) |
|-----------|-------------------|:-:|:-:|
| SvelteKit-приложение (настройка, роутинг, layout) | `frontend/` | ~1 000 | 7 |
| API-клиент (fetchApi/requestApi с токенами, ошибками) | `frontend/src/lib/api/` | ~500 | 4 |
| Система аутентификации (login, logout, token refresh) | `frontend/src/lib/auth/` | ~800 | 6 |
| WebSocket-клиент для TaskManager | `frontend/src/lib/stores/task.js` | ~400 | 3 |
| UI-kit / компонентная база (Tailwind, кнопки, формы, таблицы) | `frontend/src/lib/components/` | ~2 000 | 14 |
| i18n (русский + английский) | `frontend/src/lib/i18n/` | ~1 000 | 7 |
| **Subtotal infrastructure** | | **~5 700** | **41** |
#### 1.3 DevOps / CI / CD
| Компонент | Трудозатраты (дней) |
|-----------|:-:|
| Dockerfile + docker-compose (backend + frontend + db + redis) | 5 |
| GitHub Actions / CI (тесты, линтинг, сборка) | 3 |
| Настройка PostgreSQL, миграции, бэкапы | 2 |
| **Subtotal DevOps** | **10** |
#### 1.4 Бизнес-логика (домен перевода)
Этот компонент **общий для обоих сценариев** — чистая доменная логика, идентичная по объёму,
но в ходе реализации была значительно декомпозирована (59 plugin-файлов вместо ~14).
| Компонент | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-----:|:-:|
| ORM модели (15 таблиц) | 401 | 1 | 3 |
| Pydantic схемы (35+ DTO) | 712 | 1 | 4 |
| Plugin skeleton | 61 | 1 | 0.5 |
| **Orchestrator** (14 файлов) | 1 631 | 14 | 15 |
| **Executor** (executor, _batch_*, _llm_*, _run_*) | 2 196 | 9 | 21 |
| **Preview** (11 файлов) | 1 291 | 11 | 12 |
| **Dictionary** (7 файлов) | 921 | 7 | 9 |
| **Service** (6 файлов) | 1 281 | 6 | 11 |
| Scheduler + schedule CRUD | 443 | 1 | 5 |
| SQLGenerator | 402 | 1 | 4 |
| SupersetSqlLabExecutor | 439 | 1 | 4 |
| ContextAwarePromptBuilder | 153 | 1 | 2 |
| TranslationMetrics | 192 | 1 | 2 |
| TranslationEventLog | 274 | 1 | 3 |
| _token_budget | 395 | 1 | 4 |
| _utils | 225 | 1 | 2 |
| _lang_detect + _text_cleaner | 270 | 2 | 3 |
| _llm_async_http | 246 | 1 | 3 |
| service_target_schema | 355 | 1 | 4 |
| **Subtotal backend domain** | **~11 888** | **59** | **105** |
| API routes (13 файлов, 2 296 строк) | 2 296 | 13 | 15 |
| Frontend Svelte components (14 файлов) | 5 017 | 14 | 38 |
| Frontend pages (5 файлов) | 1 237 | 5 | 14 |
| Frontend API client (8 файлов) | 987 | 8 | 8 |
| **Subtotal frontend domain** | **~9 537** | **40** | **75** |
| **Subtotal domain logic** | **~21 425** | **99** | **180** |
#### 1.5 Enhancement Domain (Direct DB + Connections)
| Компонент | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-----:|:-:|
| ConnectionService (CRUD + шифрование + test) | 448 | 1 | 4 |
| DbExecutor (asyncpg/clickhouse-connect с пулом) | 369 | 1 | 3 |
| Connection CRUD endpoints (+5 в settings.py) | ~200 | 1 | 2 |
| ORM model updates (insert_method, connection_id, connection_snapshot) | ~100 | 2 | 1 |
| Pydantic schema updates | ~80 | 1 | 0.5 |
| Orchestrator dispatch logic (insert_method routing) | ~120 | 1 | 1 |
| Alembic migration | 34 | 1 | 0.5 |
| ConnectionsTab.svelte (Settings UI, CRUD, test button) | 385 | 1 | 3 |
| InsertMethodSelector.svelte (radio + dropdown) | 185 | 1 | 1.5 |
| API client updates (connections) | ~40 | 1 | 0.5 |
| i18n keys (en + ru, settings + translate) | ~60 | 4 | 0.5 |
| Settings page/tab registration | ~20 | 2 | 0.5 |
| **Subtotal enhancement domain** | **~2 041** | **~17** | **~18** |
#### 1.6 Тестирование
| Компонент | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-----:|:-:|
| Unit-тесты бэкенда (inline в plugin, 27 файлов) | 9 090 | 27 | 32 |
| Интеграционные тесты (external, 12 файлов) | 3 746 | 12 | 16 |
| Plugin integration (2 файла) | 279 | 2 | 2 |
| Component-тесты фронтенда (5 файлов) | 699 | 5 | 5 |
| Model-тесты фронтенда (2 файла) | 406 | 2 | 3 |
| E2E (1 файл) | 142 | 1 | 1 |
| Enhancement inline tests (6 файлов) | 1 229 | 6 | 5 |
| Enhancement external tests (3 файла) | 635 | 3 | 3 |
| Enhancement integration tests (5 файлов) | 1 015 | 5 | 4 |
| Enhancement frontend tests (1 файл) | 144 | 1 | 1 |
| **Subtotal testing** | **~17 385** | **~64** | **~72** |
#### Итог: Сценарий A
| Категория | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-----:|:-:|
| Бэкенд инфраструктура | 13 900 | — | 109 |
| Фронтенд инфраструктура | 5 700 | — | 41 |
| DevOps / CI | — | — | 10 |
| Бэкенд домен (+enhancement) | 13 929 | ~76 | 123 |
| Фронтенд домен + routes (+enhancement) | 10 118 | ~42 | 85 |
| Тесты (+enhancement) | 17 385 | ~64 | 72 |
| **ИТОГО** | **~61 032** | **~182** | **440 days** |
**Реалистичная оценка с учётом параллелизации**:
- 2 full-stack разработчика: **~78 месяцев**
- Команда (бэкенд + фронтенд + QA): **~56 месяцев**
- **Рекомендованная оценка**: **7.59.5 человеко-месяцев**
---
## 2. Сценарий B: В рамках superset-tools
### Что переиспользуется
superset-tools предоставляет **готовую отлаженную инфраструктуру**, которая в сценарии A пишется с нуля:
#### 2.1 Переиспользуемые компоненты (7 интеграционных контрактов)
| Компонент | Строк кода | Экономия (дней) | Готовность |
|-----------|:-:|:-:|:-:|
| FastAPI app + middleware + lifespan | 600 | 5 | ✅ Работает в production |
| Аутентификация (JWT, сессии, OAuth) | 2 500 | 20 | ✅ Проверена |
| RBAC (PermissionChecker, seed permissions) | 1 500 | 12 | ✅ 2543 permissions |
| SQLAlchemy Base + движок + миграции | 400 | 3 | ✅ 7 миграций |
| Plugin system (PluginBase, loader, lifecycle) | 800 | 6 | ✅ 4 плагина |
| **SupersetClient** (datasets, charts, databases, SQL Lab) | 3 500 | 25 | ✅ ~540 строк тестов |
| **LLMProviderService** (CRUD, Fernet-шифрование, OpenAI-клиент) | 1 200 | 10 | ✅ retry + fallback |
| **SchedulerService** (APScheduler, cron, load_schedules) | 600 | 5 | ✅ 3.11.2 |
| **WebSocket + TaskManager** (логгирование, прогресс, источники) | 1 200 | 10 | ✅ TaskLogRecord |
| **NotificationService** (SMTP, Telegram, Slack) | 800 | 6 | ✅ 3 провайдера |
| **Event logging** (pattern из TranslationEventLog) | 500 | 4 | ✅ Доказан |
| **Retention/pruning** (pattern из MetricSnapshot) | 300 | 3 | ✅ Доказан |
| SvelteKit приложение (lazy loading, роутинг, layouts) | 1 000 | 7 | ✅ Svelte 5 |
| API client (fetchApi, requestApi, токены) | 500 | 4 | ✅ 10+ API клиентов |
| WebSocket client (TaskManager WS) | 400 | 3 | ✅ |
| UI-kit (Tailwind, кнопки, формы, таблицы) | 2 000 | 14 | ✅ 20+ компонентов |
| i18n (en + ru, паттерн) | 1 000 | 7 | ✅ 5+ модулей перевода |
| Docker Compose (3 сервиса) | — | 5 | ✅ |
| CI (GitHub Actions) | — | 3 | ✅ |
| **ИТОГО экономия** | **~18 800** | **152 дня** | — |
#### 2.2 Что нужно построить (только домен)
> **Важно**: В ходе дальнейшей разработки код был расширен — добавились новые модули (_lang_detect, _text_cleaner, _llm_async_http, service_target_schema) и тесты.
> Общий объём кода: ~10 174 строк (plugin) + 401 (models) + 712 (schemas) = 11 287 строк в backend domain.
| Компонент | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-:|:-:|
| **Backend domain** | | | |
| ORM модели (в `models/translate.py`) | 401 | 1 | 3 |
| Pydantic схемы (в `schemas/translate.py`) | 712 | 1 | 4 |
| Plugin skeleton (plugin.py) | 61 | 1 | 0.5 |
| **Orchestrator** (14 файлов: planner, exec, sql, retry, cancel, validation, aggregator, run_completion, runner, lang_stats, query, config, sql_rows) | 1 631 | 14 | 15 |
| **Executor / LLM** (9 файлов: executor, _llm_call, _llm_parse, _llm_async_http, _batch_insert, _batch_proc, _batch_sizer, _run_service, _run_source) | 2 196 | 9 | 21 |
| **Preview** (11 файлов: executor, prompt_builder, prompt_helpers, response_parser, review, session_ops, session_serializer, token_estimator, constants, resolve_provider) | 1 291 | 11 | 12 |
| **Dictionary** (7 файлов: correction, crud, entries, filter, import_export, validation) | 921 | 7 | 9 |
| **Service** (6 файлов: bulk_replace, inline_correction, datasource, target_schema, utils) | 1 281 | 6 | 12 |
| Scheduler (+ cron utils) | 443 | 1 | 5 |
| SQLGenerator | 402 | 1 | 4 |
| SupersetSqlLabExecutor | 439 | 1 | 4 |
| PromptBuilder | 153 | 1 | 2 |
| Metrics | 192 | 1 | 2 |
| Events | 274 | 1 | 3 |
| _token_budget | 395 | 1 | 4 |
| _utils | 225 | 1 | 2 |
| _lang_detect | 207 | 1 | 2 |
| _text_cleaner | 63 | 1 | 1 |
| **Subtotal backend domain** | **~11 287** | **59** | **105** |
| **Backend routes (13 файлов)** | **2 296** | **13** | **15** |
| **Frontend UI (27 файлов)** | | | |
| Компоненты (14 svelte-файлов) | 5 017 | 14 | 38 |
| Страницы (5 svelte-файлов) | 1 237 | 5 | 14 |
| API client (8 js/ts-файлов) | 987 | 8 | 8 |
| **Subtotal frontend** | **~7 241** | **27** | **60** |
| **Enhancement domain (US11US12)** | | | |
| ConnectionService | 448 | 1 | 4 |
| DbExecutor | 369 | 1 | 3 |
| Connection CRUD (+5 endpoints в settings.py) | ~200 | 1 | 2 |
| ORM + schema updates | ~180 | 3 | 1.5 |
| Orchestrator dispatch logic | ~120 | 1 | 1 |
| Alembic migration | 34 | 1 | 0.5 |
| ConnectionsTab.svelte | 385 | 1 | 3 |
| InsertMethodSelector.svelte | 185 | 1 | 1.5 |
| API client + i18n + settings/tab reg | ~120 | 7 | 1.5 |
| **Subtotal enhancement domain** | **~2 041** | **~17** | **~18** |
| **Тесты** | | | |
| Inline plugin tests (33 файла) | 10 319 | 33 | 35 |
| External backend unit tests (~280 файлов) | ~85 000 | ~280 | 55 |
| External integration tests (15 файлов) | 4 482 | 15 | 18 |
| Plugin integration (2 файла) | 279 | 2 | 2 |
| Frontend component tests (5 файлов) | 699 | 5 | 5 |
| Frontend model tests (2 файла) | 406 | 2 | 3 |
| E2E (1 файл) | 142 | 1 | 1 |
| Enhancement inline tests (6 файлов) | 1 229 | 6 | 5 |
| Enhancement external tests (3 файла) | 635 | 3 | 3 |
| Enhancement integration tests (5 файлов) | 1 015 | 5 | 4 |
| Enhancement frontend tests (1 файл) | 144 | 1 | 1 |
| **Subtotal tests** | **~103 750** | **~353** | **~132** |
| Алембик миграции (6 файлов) | 835 | 6 | 4.5 |
| Семантические контракты + документирование | — | — | 6 |
| **Subtotal** | **~40 041** | **~182** | **~279** |
> **Примечание по effort**: Добавлены новые модули (_lang_detect, _text_cleaner, _llm_async_http, service_target_schema, connection_service, db_executor) и существенно расширены тесты (+3 023 строки, +15 файлов), что увеличило backend domain на ~10 дней, frontend на ~4.5 дня и тесты на ~13 дней.
#### Итог: Сценарий B
| Категория | Строк кода | Файлов | Трудозатраты (дней) |
|-----------|:-:|:-----:|:-:|
| Переиспользовано (бесплатно) | ~18 800 | — | 0 |
| Бэкенд домен | 11 287 | 59 | 105 |
| API routes | 2 296 | 13 | 15 |
| Фронтенд | 7 241 | 27 | 60 |
| Enhancement (US11US12) | 2 041 | ~17 | 18 |
| Тесты | 103 750 | ~353 | 132 |
| Миграции + документация | 835 | 6 | 10.5 |
| **ИТОГО** | **~127 450** | **~475** | **~340 days** |
**Реалистичная оценка с учётом параллелизации**:
- 1 full-stack разработчик (знакомый с superset-tools): **~4.55 месяцев**
- 2 разработчика (бэкенд + фронтенд): **~44.5 месяца**
- **Рекомендованная оценка**: **4.04.5 человеко-месяца**
- Примечание: рост оценки по сравнению с v1 (+1.01.5 мес.) обусловлен масштабной кампанией unit-тестирования (48% → 98.4%, +6055 тестов), что добавило ~55 дней в сценарии B. Без этой кампании оценка осталась бы на уровне 3.03.5 мес.
---
## 3. Сравнительный анализ
### 3.1 Таблица сравнения
| Измерение | Standalone (A) | В superset-tools (B) | Разница |
|-----------|:-:|:-:|:-:|
| Всего строк кода | ~61 032 | ~127 450 | +109% (тесты) |
| Из них нового кода | 100% | 83% (тесты ~81%) | — |
| Инфраструктура | 19 600 строк (32%) | 0 (переиспользовано) | -100% |
| Домен (бэк + фронт + enhancement) | 24 047 | 22 865 | -5% |
| Тесты | 17 385 | 103 750 | +497% |
| Файлов всего | ~182 | ~475 | +161% |
| Человеко-дней | 440 | 340 | -23% |
| Человеко-месяцев | 7.59.5 | 4.04.5 | -4753% |
| Рыночная стоимость* | 4.25.3 млн ₽ | 2.22.5 млн ₽ | экономия ~2.02.8 млн ₽ |
\* При ставке ~3 500 ₽/час (senior full-stack developer, РФ, фриланс/контракт). 1 человеко-месяц ≈ 160 часов ≈ 560 000 ₽.
Диапазон: 7.5 мес × 560К = 4.20 млн (min) … 9.5 мес × 560К = 5.32 млн (max) для сценария A.
Среднерыночная ставка на 20252026 гг. по данным Хабр Карьера, Kwork, fl.ru для senior-уровня.
### 3.2 Что конкретно экономит superset-tools
| Компонент | Экономия | Почему существенно |
|-----------|:-:|-------------------|
| **SupersetClient** | 25 дней | Написать клиент для /api/v1/sqllab/execute/, датасорсов, метаданных — недели отладки |
| **LLMProviderService** | 10 дней | Без него: своя БД для провайдеров, Fernet-шифрование, retry-логика, тесты |
| **RBAC/Permissions** | 12 дней | Иначе: своя таблица прав, middleware, owner-scoping, seed-скрипты |
| **SchedulerService** | 5 дней | APScheduler с BackgroundScheduler, cron-триггеры, load_schedules |
| **WebSocket/TaskManager** | 10 дней | Иначе: свой WebSocket-хаб, логика reconnect, истории сообщений |
| **NotificationService** | 6 дней | Иначе: SMTP-клиент, Telegram Bot API, Slack Webhook — всё с нуля |
| **Plugin system** | 6 дней | Иначе: свой механизм авто-дискавери и lifecycle |
| **Alembic env + Base** | 3 дня | Иначе: настройка env.py, autogenerate, SQLite-совместимость |
| **Frontend infra** | 35 дней | SvelteKit, auth, WS-клиент, UI-kit, i18n — ~35 дней на дизайн-систему |
| **Docker + CI** | 8 дней | Dockerfile, docker-compose, GitHub Actions |
| **EncryptionManager** | 3 дня | Переиспользован для шифрования паролей DB-соединений (US12) |
| **ConfigManager** | 2 дня | Переиспользован для хранения DatabaseConnection в GlobalSettings |
| **ИТОГО** | **~125 дней** | |
### 3.3 Профиль рисков
| Риск | Standalone (A) | В superset-tools (B) |
|------|:---:|:---:|
| Ошибки в интеграции с Superset API | Высокий (с нуля) | Низкий (проверено 4 плагинами) |
| Утечка API-ключей LLM | Высокий (своё шифрование) | Низкий (Fernet proven) |
| Race conditions в планировщике | Высокий (свой APScheduler) | Низкий (production experience) |
| Потеря WebSocket-соединений | Высокий (свой WS) | Низкий (TaskManager proven) |
| SQL-инъекции в генераторе | Средний (новый код) | Средний (тот же код) |
| Утечка паролей DB-соединений | Высокий (своё шифрование) | Низкий (EncryptionManager proven) |
| Семантическая задолженность | Никто не проверяет | ✅ GRACE audit |
| Прямое подключение к БД (US11) | Высокий (connection pooling с нуля) | Низкий (asyncpg + существующий ConfigManager) |
---
## 4. Статус реализации Enhancement Phase (US11US12)
### 4.1 Прогресс на 2026-06-11
Enhancement phase (Direct DB Insert + Connection Settings) в активной реализации на ветке `033-gradio-agent-chat`. Статус компонентов:
| Компонент | Статус | Файл | Строк |
|-----------|:------:|------|:-----:|
| `DatabaseConnection` (Pydantic model) | ✅ Реализован | `config_models.py` | ~50 |
| `ConnectionService` (CRUD + encrypt/test) | ✅ Реализован | `core/connection_service.py` | 448 |
| `DbExecutor` (asyncpg/clickhouse-connect) | ✅ Реализован | `core/db_executor.py` | 369 |
| Connection CRUD endpoints (+5) | ✅ Реализован | `routes/settings.py` | +~200 |
| ORM model updates (insert_method, connection_id) | ✅ Реализован | `models/translate.py` | +~100 |
| Pydantic schema updates | ✅ Реализован | `schemas/translate.py` | +~80 |
| Orchestrator dispatch (insert_method routing) | ✅ Реализован | `orchestrator_aggregator.py` и др. | +~120 |
| Alembic migration | ✅ Реализован | `c0d1e2f3a4b5_add_insert_method_and_connection_fields.py` | 34 |
| `ConnectionsTab.svelte` | ✅ Реализован | `routes/settings/ConnectionsTab.svelte` | 385 |
| `InsertMethodSelector.svelte` | ✅ Реализован | `components/translate/InsertMethodSelector.svelte` | 185 |
| API client updates | ✅ Реализован | `api/translate.ts`, `api.ts` | +~40 |
| i18n keys | ✅ Реализован | `en/ru: settings.json + translate.json` | +~60 |
| Settings page/tab registration | ✅ Реализован | `settings-utils.ts`, `+page.svelte` | +~20 |
| RBAC permission (`settings.connections.manage`) | ✅ Реализован | `seed_permissions.py` | — |
| `requirements.txt` (asyncpg, clickhouse-connect) | ✅ Реализован | `requirements.txt` | — |
| Inline plugin tests (6 новых файлов) | ✅ Реализован | `__tests__/test_batch_insert.py` и др. | 1 229 |
| External tests (3 новых файла) | ✅ Реализован | `test_connection_service.py` и др. | 635 |
| Integration tests (5 новых файлов) | ✅ Реализован | `test_superset_sqllab_e2e.py` и др. | 1 015 |
| Frontend tests (InsertMethodSelector) | ✅ Реализован | `InsertMethodSelector.test.ts` | 144 |
### 4.2 Оставшиеся задачи (Tasks T135T160)
Из 26 запланированных enhancement-задач основная реализация выполнена. Остаются:
- **Верификация**: прогон полного набора тестов (`pytest`, `vitest`), семантический аудит
- **Quickstart**: обновление quickstart.md для flow direct DB insert
- **Документирование**: актуализация spec-файлов по факту реализации
---
## 5. Расхождение спецификации и реализации
В ходе анализа выявлены существенные расхождения между spec/plan и фактической реализацией:
### 5.1 Архитектурные расхождения
| Аспект | Как описано в spec/plan | Как реализовано | Критичность |
|--------|------------------------|-----------------|:-----------:|
| **Тип архитектуры** | Plugin-based (`TranslatePlugin.execute()` — основной entry point) | **Service-based**: Plugin только скелет (raise NotImplementedError), вся логика в сервисах | 🔴 Высокая |
| **Файл роутера** | `backend/src/api/routes/translate.py` (один файл) | `backend/src/api/routes/translate/` (пакет, 13 файлов) | 🟡 Средняя |
| **Файлы не из плана** | _token_budget.py, _utils.py, _helpers.py, prompt_builder.py, superset_executor.py, service.py | Существуют, но не описаны | 🟡 Средняя |
| **Компоненты не из плана** | CorrectionCell.svelte, BulkReplaceModal.svelte, TranslationRunGlobalIndicator.svelte, TranslationMetricsDashboard.svelte, translateStore.js | Существуют, но не описаны | 🟡 Средняя |
| **Plugin skeleton** | C3 с полной функциональностью | C2 с NotImplementedError | 🟢 Низкая (регистрационный артефакт) |
| **Connection storage** | Отдельная таблица БД | В `GlobalSettings.connections` (Pydantic model) | 🟢 Низкая (config persistence pattern) |
### 5.2 Расхождения в семантических контрактах
| Контракт | Spec (C?) | Reality (C?) | Файл |
|----------|:---------:|:------------:|------|
| `TranslatePlugin:Module` | C3 | C2 | plugin.py |
| `TranslateRoutes:Module` | C3 | C4 | `__init__.py` |
| `TranslateRouterModule` | не описан | C1 | `_router.py` |
| `SQLGenerator:Class` | C4 | C3 | sql_generator.py |
| `SupersetSqlLabExecutor:Class` | не описан | C3 | superset_executor.py |
| `ContextAwarePromptBuilder:Class` | C3 | существует | prompt_builder.py |
| `InlineCorrectionService:Class` | C4 | C3 (de facto) | service.py |
| `BulkFindReplaceService:Class` | C4 | C3 (de facto) | service.py |
| `TranslateJobService:Class` | не описан | C4 | service.py |
| `ConnectionService:Class` | не описан | C3 (NEW) | connection_service.py |
| `DbExecutor:Class` | не описан | C3 (NEW) | db_executor.py |
### 5.3 Спецификация API / quickstart
- **Quickstart**: Использует `target_language: "ru"` (single-language API) вместо `target_languages: ["ru"]`
- **Quickstart**: Путь тестов `backend/tests/test_translate_api.py` не существует (реальность: `test_translate_jobs.py` и др.)
- **Quickstart**: `ruff check` использует неверный путь `src/api/routes/translate.py` (должен быть `src/api/routes/translate/`)
- **Quickstart**: Отсутствует flow для Direct DB insert (US11) и Connection Settings (US12)
---
## 6. Выводы
### Для бизнеса
1. **Строить в superset-tools выгодно**: экономия ~4753% стоимости и времени (с поправкой на масштабную кампанию тестирования)
2. **Standalone не имеет смысла** для этого функционала: 32% кода — инфраструктура, которая уже есть в superset-tools
3. **Качество выше в superset-tools** за счёт переиспользования проверенных компонентов (RBAC, LLM, WebSocket, EncryptionManager) и **98.4% покрытия unit-тестами** (7778 тестов)
4. **Enhancement phase** (Direct DB + Connections) добавляет ~1011 рабочих дней при реализации в superset-tools — незначительно по сравнению с ~20 днями в standalone
5. **Кампания тестирования** (48% → 98.4%) эквивалентна ~55 дням работы одного разработчика, но окупается снижением рисков регрессий и ускорением будущих рефакторингов
### Для команды
1. **Реализация заняла бы 4.04.5 месяца** в superset-tools против 7.59.5 standalone (с учётом полной кампании тестирования)
2. **Основная сложность** — не инфраструктура, а доменная логика (executor, orchestrator, обработка LLM-ответов)
3. **Код был существенно расширен** в процессе дальнейшей разработки: 59 файлов plugin → +17 enhancement, 184 → 475 файлов всего (~291 новых тестовых файлов), ~40K → ~127K строк (~87K тестов)
4. **Покрытие тестами**: backend unit-тесты выросли с ~1723 (48%) до 7778 (98.4% real coverage) — кампания из ~4 сессий с ~25 параллельными агентами
5. **Самые сложные модули** (по совокупному объёму):
- `Orchestrator` (1 631 строка, 14 файлов, 15 дней) — координация run lifecycle + dispatch insert_method
- `Executor + LLM` (2 196 строк, 9 файлов, 21 день) — парсинг LLM-ответов, батчинг, retry, caching
- `Preview` (1 291 строка, 11 файлов, 12 дней) — quality gate, approve/edit/reject lifecycle
- `Dictionary` (921 строка, 7 файлов, 9 дней) — CRUD + import/export + per-batch filtering
- `Service` (1 281 строка, 6 файлов, 12 дней) — job coordination, target schema, inline correction
- `ConnectionService` + `DbExecutor` (817 строк, 2 файла, 7 дней) — native DB drivers, pooling, encryption [NEW]
### Рекомендации по актуализации specks
- spec.md: статус → "Implemented ✅ + Enhancement ✅", обновить секцию Implementation Notes
- plan.md: исправить file path (package vs single file), добавить недостающие модули, отразить enhancement
- contracts/modules.md: выровнять @COMPLEXITY с реальностью, добавить новые контракты (ConnectionService, DbExecutor)
- quickstart.md: обновить примеры API на multi-language, добавить flow для Direct DB insert
- tasks.md: обновить closure summary, отметить enhancement tasks как [x]
- effort-estimate-report.md: ✅ актуализирован (этот документ)
---
## Приложение A: Детальный breakdown по файлам (актуальная реализация)
> В ходе дальнейшей разработки код был расширен: добавлены новые модули, расширены тесты, реализован enhancement (US11US12).
> Общий объём кода: 74 файла backend source + 27 frontend source + 64 тестов + 17 enhancement = 182 файлов, ~40 041 строк.
### Бэкенд (74 файла source + 17 enhancement + 62 файла тестов, ~13 585 source + ~2 041 enhancement + ~14 415 тестов)
#### Plugin core (59 файлов, 10 174 строк source)
**Orchestrator (14 файлов, 1 631 строка)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `orchestrator.py` | 175 | Entry point / facade |
| `orchestrator_planner.py` | 127 | Run planning: target langs, batches |
| `orchestrator_exec.py` | 121 | Translation execution coordinator |
| `orchestrator_sql.py` | 118 | SQL generation stage |
| `orchestrator_sql_rows.py` | 115 | Row fetch + pagination |
| `orchestrator_aggregator.py` | 139 | Results aggregation (+insert_method dispatch) |
| `orchestrator_retry.py` | 136 | Retry logic for failed batches |
| `orchestrator_cancel.py` | 120 | Run cancellation |
| `orchestrator_validation.py` | 61 | Post-run validation |
| `orchestrator_run_completion.py` | 139 | Run finalization (status, error_message) |
| `orchestrator_runner.py` | 76 | Background task runner |
| `orchestrator_lang_stats.py` | 87 | Per-language statistics |
| `orchestrator_query.py` | 148 | Query builder / data source queries |
| `orchestrator_config.py` | 69 | Configuration merging |
**Preview (11 файлов, 1 291 строка)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `preview.py` | 286 | Main facade: run, accept, reject |
| `preview_executor.py` | 149 | LLM call orchestration |
| `preview_prompt_builder.py` | 133 | Prompt construction per language |
| `preview_prompt_helpers.py` | 111 | Prompt formatting utilities |
| `preview_response_parser.py` | 158 | Parse LLM responses |
| `preview_review.py` | 136 | Quality gate / approval logic |
| `preview_session_ops.py` | 94 | Preview session persistence |
| `preview_session_serializer.py` | 101 | Session serialize/deserialize |
| `preview_token_estimator.py` | 51 | Token budget estimation |
| `preview_constants.py` | 48 | Constants / defaults |
| `preview_resolve_provider.py` | 24 | LLM provider resolution |
**Executor / Batch / LLM (9 файлов, 2 196 строк)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `executor.py` | 272 | Main facade: batch dispatch, caching |
| `_llm_call.py` | 540 | Centralized LLM call with retry + fallback |
| `_llm_parse.py` | 116 | Parse LLM streamed responses |
| `_llm_async_http.py` | 246 | Async HTTP transport for LLM APIs |
| `_batch_insert.py` | 246 | Insert results to Superset datasource |
| `_batch_proc.py` | 259 | Batch processing coordination |
| `_batch_sizer.py` | 201 | Dynamic batch sizing by token budget |
| `_run_service.py` | 175 | Run create/update/status queries |
| `_run_source.py` | 141 | Source row fetching + pagination |
**Dictionary (7 файлов, 921 строка)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `dictionary.py` | 63 | Facade / re-exports |
| `dictionary_crud.py` | 129 | Create, read, update entries |
| `dictionary_entries.py` | 184 | Entry query + filtering |
| `dictionary_filter.py` | 140 | Per-batch dynamic filter construction |
| `dictionary_correction.py` | 192 | Correction CRUD + batch apply |
| `dictionary_import_export.py` | 196 | CSV import/export |
| `dictionary_validation.py` | 17 | Entry validation rules |
**Service (6 файлов, 1 281 строка)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `service.py` | 274 | Job CRUD + run coordination |
| `service_inline_correction.py` | 221 | Inline correction orchestration |
| `service_bulk_replace.py` | 189 | Bulk find-and-replace |
| `service_datasource.py` | 171 | Datasource metadata service |
| `service_target_schema.py` | 355 | Target schema management |
| `service_utils.py` | 71 | Shared service utilities |
**Standalone modules (12 файлов, 2 854 строки)**
| Файл | Строк | Сложность | Назначение |
|------|:-----:|:---------:|------------|
| `scheduler.py` | 443 | C4 | Schedule CRUD + APScheduler dispatch |
| `superset_executor.py` | 439 | C3 | Superset SQL Lab API client |
| `sql_generator.py` | 402 | C3 | Dialect-aware SQL generation |
| `_token_budget.py` | 395 | C2 | Token estimation |
| `_lang_detect.py` | 207 | C2 | Language detection for SQL |
| `_utils.py` | 225 | C1 | Shared utilities |
| `events.py` | 274 | C3 | Structured event log + pruning |
| `metrics.py` | 192 | C2 | Metrics aggregation |
| `prompt_builder.py` | 153 | C3 | Context-aware prompt construction |
| `_text_cleaner.py` | 63 | C1 | Text sanitization utilities |
| `plugin.py` | 61 | C2 | Plugin skeleton |
| `__init__.py` | 2 | — | Package marker |
#### Enhancement: Core Services (2 файла, 817 строк) 🆕
| Файл | Строк | Сложность | Назначение |
|------|:-----:|:---------:|------------|
| `core/connection_service.py` | 448 | C3 | Connection CRUD, encrypt/decrypt, test connectivity |
| `core/db_executor.py` | 369 | C3 | Direct DB execution: asyncpg + clickhouse-connect, pooling |
#### Routes (13 файлов, 2 296 строк)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `__init__.py` | 42 | Package init + router registration |
| `_router.py` | 13 | APIRouter instance |
| `_job_routes.py` | 285 | Job CRUD endpoints |
| `_run_routes.py` | 205 | Run execution endpoints |
| `_run_list_routes.py` | 359 | Run list/detail/CSV |
| `_run_edit_routes.py` | 200 | Run edit endpoints |
| `_run_history_routes.py` | 133 | Run history endpoints |
| `_preview_routes.py` | 194 | Preview endpoints |
| `_dictionary_routes.py` | 391 | Dictionary endpoints |
| `_correction_routes.py` | 100 | Correction endpoints |
| `_schedule_routes.py` | 239 | Schedule endpoints |
| `_metrics_routes.py` | 65 | Metrics endpoints |
| `_helpers.py` | 70 | Response helpers |
#### Models + Schemas (2 файла, 1 113 строк)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `models/translate.py` | 401 | 15 ORM моделей (+insert_method, +connection_id, +connection_snapshot) |
| `schemas/translate.py` | 712 | 35+ Pydantic схем (+insert_method, +connection_id) |
#### Миграции (6 файлов, ~835 строк)
#### Тесты бэкенда
**Inline plugin tests (27 + 6 enhancement = 33 файла, 10 319 строк)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `test_orchestrator.py` | 884 | Orchestrator unit tests |
| `test_dialect_detection_orthogonal.py` | 932 | Dialect/edge case detection |
| `test_inline_correction.py` | 792 | Inline correction tests |
| `test_executor.py` | 698 | Executor + LLM call tests |
| `test_orthogonal_fixes.py` | 624 | Edge case + regression tests |
| `test_clickhouse_insert_integration.py` | 546 | CH insert integration |
| `test_target_schema.py` | 462 | Target schema tests |
| `test_preview.py` | 425 | Preview engine tests |
| `test_scheduler.py` | 407 | Scheduler unit tests |
| `test_sql_generator.py` | 368 | SQL generation tests |
| `test_batch_classify_persist.py` | 362 | Batch classification tests |
| `test_dictionary_filter.py` | 341 | Dynamic filter tests |
| `test_run_service.py` 🆕 | 295 | Run service tests |
| `test_token_budget.py` | 284 | Token estimation tests |
| `test_dictionary_crud.py` | 271 | Dictionary CRUD tests |
| `test_dict_snapshot_hash.py` | 240 | Dictionary hash tests |
| `test_batch_insert.py` 🆕 | 232 | Batch insert tests |
| `test_sql_insert_service.py` 🆕 | 221 | SQL insert service tests |
| `test_lang_detect.py` | 212 | Language detection tests |
| `test_response_field_coverage.py` 🆕 | 181 | Response field coverage |
| `test_dictionary_import.py` | 177 | Import/export tests |
| `test_metrics_cumulative.py` | 177 | Metrics cumulative tests |
| `test_lang_stats.py` 🆕 | 168 | Language statistics tests |
| `test_batch_sizer.py` | 155 | Batch sizing tests |
| `test_enforce_dictionary.py` | 168 | Dictionary enforcement tests |
| `test_retry.py` 🆕 | 132 | Retry logic tests |
| `test_dictionary_correction.py` | 124 | Correction tests |
| `test_dictionary_prompt_builder.py` | 111 | Prompt builder tests |
| `test_text_cleaner.py` | 186 | Text cleaner tests |
| `test_dictionary_utils.py` | 36 | Dictionary utility tests |
| `test_dictionary.py` | 20 | Dictionary facade tests |
**External integration tests (10 + 5 enhancement = 15 файлов, 4 482 строки)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `test_translate_jobs.py` | 563 | API job lifecycle |
| `test_core_scheduler.py` | 518 | Core scheduler tests |
| `test_translate_history.py` | 467 | History API |
| `test_translate_scheduler_execution.py` | 399 | Execution integration |
| `core/test_async_regression.py` | 370 | Async regression tests |
| `test_translate_scheduler_guard.py` | 298 | Guard/validation |
| `test_translate_executor_filter.py` | 289 | Executor filter logic |
| `test_translate_corrections.py` | 249 | Correction API |
| `test_translate_scheduler.py` | 195 | Scheduler integration |
| `test_translate_status_fk.py` 🆕 | 245 | Status FK tests |
| `test_translate_schedules.py` 🆕 (integration) | 235 | Schedule integration |
| `test_superset_sqllab_e2e.py` 🆕 | 227 | SQL Lab E2E |
| `test_translate_clickhouse.py` 🆕 | 181 | ClickHouse integration |
| `test_translate_corrections.py` 🆕 (integration) | 127 | Correction integration |
| `test_alembic_migrations.py` | 119 | Migration tests |
**Plugin external integration tests (2 файла, 279 строк)**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `test_llm_async.py` | 193 | LLM async integration tests |
| `test_async_concurrency.py` | 86 | Async concurrency tests |
**Enhancement external tests (3 файла, 635 строк) 🆕**
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `test_connection_service.py` | 312 | ConnectionService CRUD + encrypt + test |
| `test_orchestrator_direct_db.py` | 196 | Orchestrator direct DB dispatch |
| `test_db_executor.py` | 127 | DbExecutor asyncpg/clickhouse-connect |
### Фронтенд (27 файлов source + 8 файлов тестов + 3 enhancement, ~7 241 source + ~1 247 тестов + ~714 enhancement)
#### Компоненты (14 + 1 enhancement = 15 файлов, 5 202 строки)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `TranslationPreview.svelte` | 561 | Preview component (quality gate) |
| `TranslationRunResult.svelte` | 464 | Run result display |
| `BulkReplaceModal.svelte` | 396 | Find-and-replace modal |
| `RunTabContent.svelte` | 370 | Run tab content |
| `TargetTabForm.svelte` | 358 | Target language tab form |
| `TermCorrectionPopup.svelte` | 342 | Single correction popup |
| `CorrectionCell.svelte` | 326 | Inline editable cell |
| `TranslationRunProgress.svelte` | 310 | Live progress with retry |
| `ScheduleConfig.svelte` | 286 | Schedule editor |
| `BulkCorrectionSidebar.svelte` | 285 | Bulk correction panel |
| `ConfigTabForm.svelte` | 274 | Configuration tab form |
| `TranslationRunGlobalIndicator.svelte` | 198 | Global run indicator |
| `TranslationMetricsDashboard.svelte` | 184 | Metrics dashboard |
| `InsertMethodSelector.svelte` 🆕 | 185 | Insert method selector (sqllab / direct DB) |
| `TargetSchemaHint.svelte` | 62 | Target schema hint tooltip |
#### Страницы (5 файлов, 1 237 строк)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `[id]/+page.svelte` | 1 363 | Job detail (config + run + results) |
| `dictionaries/[id]/+page.svelte` | 821 | Dictionary editor |
| `history/+page.svelte` | 523 | Run history |
| `dictionaries/+page.svelte` | 270 | Dictionary list |
| `+page.svelte` | 279 | Job list |
#### Settings (1 файл, 385 строк) 🆕
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `routes/settings/ConnectionsTab.svelte` | 385 | Connection management: list, add, edit, test, delete |
#### API client (7 + 1 enhancement = 8 файлов, ~869 строк)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `translate.ts` | 382 | Main translate API client (+connections methods) |
| `target-schema.ts` | 83 | Target schema API |
| `runs.js` | — | Run status/control API |
| `jobs.js` | — | Job CRUD API |
| `dictionaries.js` | — | Dictionary CRUD API |
| `corrections.js` | — | Correction API |
| `schedules.js` | — | Schedule API |
| `datasources.js` | — | Datasource API |
#### Store + i18n (2 файла, 377 строк)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `translationRun.js` | 198 | Run state store |
| `i18n/index.ts` | 179 | en + ru translation keys |
#### Frontend-тесты (8 + 1 enhancement = 9 файлов, 1 391 строка)
| Файл | Строк | Назначение |
|------|:-----:|------------|
| `tests/TranslationJobModel.test.ts` | 354 | Job model tests |
| `tests/test_translation_preview.svelte.js` | 199 | Preview component tests |
| `tests/TargetSchemaHint.test.ts` | 158 | Target schema hint tests |
| `tests/InsertMethodSelector.test.ts` 🆕 | 144 | Insert method selector tests |
| `tests/test_correction_cell.svelte.js` | 136 | CorrectionCell tests |
| `tests/test-target-schema.test.ts` | 109 | Target schema API tests |
| `tests/test_bulk_replace_modal.svelte.js` | 97 | BulkReplace modal tests |
| `tests/TranslateHistoryModel.test.ts` | 52 | History model tests |
| `translation.e2e.js` | 142 | E2E: create run, check progress |
---
*Отчёт сгенерирован по результатам анализа spec-файлов и реализованного кода feature 028.
Актуализация 2026-06-16: добавлен enhancement phase (US11US12), обновлены метрики тестового покрытия (48% → 98.4%, +6055 тестов), скорректированы оценки трудозатрат с учётом кампании unit-тестирования.*