Commit Graph

469 Commits

Author SHA1 Message Date
db7e5e3863 feat(translate): add WebSocket endpoint for real-time run progress
Backend:
- Add /ws/translate/run/{run_id} WebSocket endpoint in app.py
- Streams structured run status every second (total_records,
  successful_records, failed_records, progressPct, batch_count, etc.)
- Auto-detects terminal states (COMPLETED, FAILED, CANCELLED) and closes
- Authenticated via JWT/API key token query param

Frontend:
- Add getTranslateRunWsUrl() URL builder in api.js
- Update translationRunStore to use WebSocket instead of log stream
- WebSocket receives structured status JSON, updates store reactively
- Falls back to polling silently if WebSocket fails
- Keep polling as fallback for insert phase
2026-05-29 16:42:59 +03:00
1aceba465b fix: remove orphaned functions, add for auto-load columns
Clean up remaining orphaned references after tab extraction:
- Remove loadColumnsForDatasource, searchDatasources, selectDatasource
  etc. from page (moved to ConfigTabForm)
- Add  on datasourceId in ConfigTabForm for auto-loading
  columns when parent sets datasourceId (loadJob)
- Fix stray braces, remove dead isVirtual function
- Page now 779 lines (down from 1519, -49%)
2026-05-29 16:35:50 +03:00
ffa6234a36 refactor: remove orphaned functions after tab extraction
Remove loadColumnsForDatasource, searchDatasources, selectDatasource,
toggleContextColumn, toggleSourceKeyCol, updateTargetKeyCol, isVirtual
from page — all moved to ConfigTabForm.svelte.

Add  on datasourceId in ConfigTabForm to auto-load columns
when parent sets datasourceId (loadJob) or user selects a datasource.
2026-05-29 16:33:15 +03:00
ebc00bbb0e refactor(translate): extract ConfigTabForm, TargetTabForm, RunTabContent from page
Page reduced from 1519 to 909 lines (-40%). Extracted:
- ConfigTabForm.svelte (370 lines) — datasource search, column mapping,
  LLM, target languages, dictionaries, batch config
- TargetTabForm.svelte (120 lines) — target schema/table/database,
  target column mapping, TargetSchemaHint
- RunTabContent.svelte (170 lines) — run cards, progress, history

All three components use () props for seamless parent
state sync. Sub-components (TargetSchemaHint, TranslationPreview,
TranslationRunProgress, ScheduleConfig, BulkReplaceModal) unchanged.
2026-05-29 16:30:09 +03:00
05fda8310d refactor(translate): add UX contracts to translation job page
Add comprehensive UX contract header documenting:
- @UX_STATE: all states of the page-level state machine (idle, loading,
  configured, saving, validation_error, datasource_unavailable, error)
- @UX_STEP: 5 logically separated steps/tabs (Config, Preview, Target, Run, Schedule)
- @UX_FEEDBACK: toasts, modals, inline progress, schema validation
- @UX_RECOVERY: retry paths for save/preview/run failures
- @UX_REACTIVITY: props, local state, derived, effects, store bindings
- @UX_DEPENDENCY: data flow between datasource selection, env switching,
  config validity, and tab availability
- @UX_TEST: test scenarios for the automated Judge Agent

Also remove leftover sourceDialect/targetDialect selects from UI
(now sent as sensible defaults in save payload).

Sub-components (TargetSchemaHint, TranslationPreview, TranslationRunProgress,
ScheduleConfig, BulkReplaceModal) already have UX contracts.
2026-05-29 16:25:14 +03:00
c9fb994728 fix(translate): remove source/target dialect selects from UI
These fields were showing database types (PostgreSQL, ClickHouse)
as human language options for the LLM prompt, which was confusing.
Now sending sensible defaults (source='SQL', target='en') directly
in the save payload without exposing them in the UI.

The backend already has fallbacks:
  _llm_call.py: source_language = job.source_dialect or 'SQL'
  _batch_proc.py: target_langs = or [job.target_dialect or 'en']
2026-05-29 16:16:05 +03:00
5deb01e182 fix 2026-05-29 16:15:41 +03:00
e7d4121dc9 fix(translate): replace DB types with human languages in source/target dialect selects
sourceDialect/targetDialect select options contained database types
(PostgreSQL, ClickHouse, MySQL...) while these fields are used as
human language indicators for the LLM prompt:
  _llm_call.py: source_language = job.source_dialect or 'SQL'

Changed to use the existing LANGUAGES list (from LANGUAGE_LABELS:
ru, en, de, fr, es, etc.) plus 'SQL' option for source dialect.
Defaults updated: source='SQL' (SQL-like expressions), target='en'.
2026-05-29 16:14:49 +03:00
b850fad7a7 fix(translate): restore environmentId before loading databases in loadJob
Bug: loadDatabases() was called at line 374 while environmentId still
held the FIRST environment from initialization (line 259), because
environmentId = j.environment_id was not set until line 391 (inside
the datasource block). Only after that was environmentId correct.

This caused the database dropdown to show databases from a different
environment than the job's actual environment. For example, db_id=2
is DEV Greenplum in 'dev' but Prod Clickhouse in 'preprod'. The user
would select Greenplum from the dev list, but the job would use
preprod where db_id=2 is ClickHouse.

Fix: set environmentId from the job's stored environment BEFORE
calling loadDatabases(), and outside the datasource conditional
so it runs for all existing jobs.
2026-05-29 16:11:10 +03:00
525e0a56af fix(translate): add database_id to datasources response + auto-select on frontend
Root cause: fetch_available_datasources did not return database_id,
so frontend could not auto-set target_database_id when user selected
a datasource. User then had to manually pick a database on Target Config
tab — and could accidentally select the wrong one.

Backend changes:
- Add 'database_id' field to datasources response (from db_info.get('id'))
- Add _database_name tracking in SupersetSqlLabExecutor with getter
- Add database_name + database_backend to TargetSchemaValidationResponse
- Enrich resolve_database_id logging with database_name and all_keys

Frontend changes:
- In selectDatasource(), auto-set targetDatabaseId from ds.database_id
  when present, so the correct target DB is used for schema checks.
2026-05-29 15:36:36 +03:00
443751741b fix: .pem -> .crt extension for downloaded certs, remove stale check_llm_certs.txt 2026-05-29 14:32:45 +03:00
6743b67605 fix(translate): normalize backend dialect detection with explicit mapping
- Replace fragile substring check (any(kw in backend for kw in ('clickhouse', 'ch')))
  with a proper _backend_normalize mapping + exact comparison.
  Fixes misdetection of Greenplum (postgresql) and other backends.
- Add 'clickhousedb' to CLICKHOUSE_DIALECTS so SQL generator uses
  backtick quoting and correct INSERT strategy for ClickHouse.
- Normalize _extract_dialect to map 'clickhousedb' -> 'clickhouse'
  and 'greenplum' -> 'postgresql'.
2026-05-29 14:32:00 +03:00
745c9e7ef2 docs: update ADR-0009 with complete discovery journey
Added Phase 1-3 discovery timeline (certifi → .pem→.crt → cafile→capath),
OpenSSL 3.x cafile limitation analysis, diagnostic matrix,
test commands, version history. All 8 findings documented.
2026-05-29 14:30:33 +03:00
d294e0295b fix: QA findings — GRACE contracts for _get_verify, fix _llm_http.py structure
- Added #region/#endregion contracts with @RATIONALE/@REJECTED to
  _get_verify() in both translate plugins (P1 HIGH, P2 MEDIUM)
- Removed orphaned duplicates #endregion in _llm_http.py (P1 HIGH, P6 HIGH)
2026-05-29 11:10:11 +03:00
8ecea09222 fix: capath instead of cafile for all LLM clients
OpenSSL 3.x ignores intermediate CA certs in -CAfile (verify code 20)
but correctly builds chains with -CApath (verify code 0).
All three clients now use capath:
  - service.py: ssl.create_default_context(capath=...)
  - _llm_http.py: verify='/etc/ssl/certs/'
  - preview_llm_client.py: verify='/etc/ssl/certs/'
check_llm_certs.py rewritten for clarity.
2026-05-29 11:02:48 +03:00
802727b58a fix: check_llm_certs.py — fixes from user review
- openssl s_client: stdin=EOF to prevent hang (input='')
- argparse for --target CLI argument
- in_bundle check: awk+openssl per-cert fingerprint comparison
- NamedTemporaryFile: mode='wb' for binary writes
- Added httpx_capath and requests_cafile_capath tests
- Graceful handling of empty ca-certificates.crt
2026-05-28 23:22:53 +03:00
8a815ab1b1 fix: check_llm_certs.py — handle DER files, openssl timeout 20s, binary PEM reads 2026-05-28 23:10:18 +03:00
05f42d5489 fix: check_llm_certs.py — clean main() structure, safe imports 2026-05-28 22:58:37 +03:00
ed4ac88c3d feat: rewrite SSL diag in Python — tests all real libraries
Tests all 4 SSL methods with actual project libraries:
  - httpx (verify=True/False/SSLContext cafile/cafile+capath)
  - requests (verify=True/False/cafile/capath)
  - openssl s_client (default/CAfile/CApath/chain bundle)
  - certutil (NSS/Chromium)
  - certifi vs system CA comparison
Outputs JSON summary with AI diagnosis hint.
2026-05-28 22:57:08 +03:00
2cc2896740 fix: rewrite check_llm_certs.sh — tests all methods AI needs
Tests 4 variants: openssl s_client (CAfile, CApath, default),
Python httpx (cafile, cafile+capath), requests (cafile, capath),
NSS certutil. Output format is machine-parseable for AI diagnosis.
2026-05-28 22:56:19 +03:00
2d4b60cef9 feat: add SSL certificate diag script (check_llm_certs.sh)
Runs from inside Docker container to verify all 4 SSL layers:
1. System CA store (openssl s_client)
2. NSS database (certutil) for Chromium
3. Python httpx (SSLContext with cafile)
4. Python requests (verify with system CA path)
Reads LLM_SSL_VERIFY and CA paths from .env.enterprise-clean
2026-05-28 12:13:44 +03:00
19dd447345 feat: ADR-0009 SSL cert management, fix certifi vs system CA
- ADR-0009: comprehensive SSL certificate management strategy
- _get_ssl_verify() returns SSLContext with cafile= instead of bool True
  (httpx deprecates verify=<str>, requests needs system CA, not certifi)
- _get_verify() in translate plugin returns system CA path
- All tests updated for SSLContext return type
- All QA findings C1-C3, H1-H4, M1 incorporated into ADR
2026-05-28 12:06:42 +03:00
60333bdb95 fix: add LLM_SSL_VERIFY support to translate plugin HTTP clients
preview_llm_client.py and _llm_http.py both use requests.post()
without verify=, causing SSLError when corporate CA not in trust store.
Added _get_verify() helper that reads LLM_SSL_VERIFY env var.
2026-05-28 11:53:17 +03:00
477e30a9f2 git 2026-05-27 23:24:12 +03:00
d2c60c87e2 fix: QA findings C1-C3, H1-H4, M1 — cert install hardening
C1: fingerprint (SHA256) вместо grep -qF для детекции сертификатов в bundle
    — исключает ложные срабатывания и бесконечный рост ca-certificates.crt
C2: hash symlink collision — поддержка .0, .1, .2 суффиксов вместо
    перезаписи единственного .0
C3: NSS nickname collision — дедупликация по fingerprint, префикс
    директории (llm-/custom-) в nickname, fallback с хешем при коллизии
H1: DER->PEM конвертация — добавлена || проверка ошибки
H2: Удалён install_playwright из entrypoint (Chromium уже baked в Dockerfile)
H3: NSS DB path — sql: префикс, проверка существования и пересоздание
    при повреждении
H4: Chicken-and-egg TLS — curl fallback с --insecure при первом скачивании
    корп. CA сертификата
M1: nullglob для install_certificates — безопасная итерация по файлам
2026-05-27 21:50:07 +03:00
3619a2ae78 feat(assistant): implement tool registry and expand assistant capabilities
Introduce a centralized tool registry system for the assistant to manage
executable operations, permissions, and tool catalogs. This refactors
the assistant dispatch logic from a monolithic approach to a modular,
decorator-based registry.

Key changes:
- Implement `AssistantToolRegistry` to handle tool registration,
  permission checks, and safe operation identification.
- Add a suite of new assistant tools: backup, commit, branch creation,
  deployment, health summary, environment listing, LLM operations,
  maintenance, migration, and dashboard searching.
- Refactor `_dispatch.py` and `_llm_planner.py` to utilize the new
  registry for intent resolution and tool catalog building.
- Enhance the LLM planner to support more descriptive clarification
  responses in Russian when intents are ambiguous.
- Update the frontend to support the new tool-based workflow, including
  improved i18n labels for assistant operations and a new step-by-step
  wizard for the migration page.
- Add ADR-0008 to document the architectural decision for the tool
  registry.
2026-05-27 18:05:28 +03:00
8db2b1bb6b fix: replace hardcoded UI labels with i18n translations
- Add missing i18n keys to common.json, reports.json, dashboard.json,
  tasks.json, git.json (EN + RU)
- Replace all hardcoded labels in LLM report page with .reports.* keys
- Replace hardcoded tab labels (Linked resources, Git history) in
  DashboardDetail page
- Replace hardcoded RU text in DashboardGitManager with .git.* keys
- Remove hardcoded fallback strings from DashboardHeader, DashboardTaskHistory
2026-05-27 16:53:20 +03:00
040d333d7d fix: QA findings — Dockerfile #endregion dedup, @RATIONALE, grep -qF
- Removed duplicate #endregion in backend.Dockerfile (P6 critical)
- Added @RATIONALE and @REJECTED to install_ca_to_nss and install_llm_ca_certs
- Changed grep -q to grep -qF in install_llm_ca_certs validation
2026-05-27 16:12:37 +03:00
ce49760e5a date fx 2026-05-27 16:05:04 +03:00
0d05a0bd6d fix: add NSS cert import for Chromium Playwright + libnss3-tools
- install_ca_to_nss() — imports corporate CA certs into Chromium's NSS
  database (~/.pki/nssdb), fixing ERR_CERT_AUTHORITY_INVALID in Playwright
- libnss3-tools added to Dockerfile for certutil binary
2026-05-27 15:43:27 +03:00
79370f3451 fix: pass LLM_SSL_VERIFY env var through docker-compose to container 2026-05-27 15:26:38 +03:00
7ffddff2a6 feat: add LLM SSL verify control and auto CA cert download
- LLM_SSL_VERIFY env var to disable SSL verification for corporate proxies
- install_llm_ca_certs() entrypoint function — downloads PEM/DER certs
  from LLM_CA_CERT_URLS, converts DER→PEM, installs to system CA store
- _format_connection_error() — detailed exception chain logging
- 7 new unit tests for _get_ssl_verify, _format_connection_error, verify= param
- LLM_CA_CERT_URLS and LLM_SSL_VERIFY in .env.enterprise-clean
- Removed duplicate @RELATION DEPENDS_ON -> [EXT:Library:tenacity]
2026-05-27 14:44:46 +03:00
55c7e323c4 fix: test assertions for molecular CoT markers, separate propagate=False to ConfigManager, fix ruff in env.py 2026-05-27 11:26:14 +03:00
143ab15744 fix: logging overhaul — Alembic fileConfig disable_existing_loggers=False, propagate=False on loggers, ADR docs, catch-up migration for missing columns, sqlparse dep, build archive naming 2026-05-27 11:19:12 +03:00
614bf9123a log fix 2026-05-27 10:49:06 +03:00
c9d720f29a fix: bypass broken logger.isEnabledFor in log_requests middleware
After configure_logger() runs, logger.isEnabledFor(logging.INFO)
returns False despite level=10 (DEBUG). This is a CPython logging
framework anomaly that makes logger.info() silently drop messages.

Workaround: check isEnabledFor first; if False, write JSON directly
to sys.stderr bypassing the logging system entirely.
2026-05-27 10:32:42 +03:00
7aa3bd52ef fix: add PYTHONUNBUFFERED=1 to run.sh to prevent stderr buffering
Without PYTHONUNBUFFERED, when stderr is piped through '2>&1 | sed',
Python fully buffers stderr output. JSON log lines are small and never
fill the buffer, so they never appear in real time (or at all for
sporadic HTTP request logs). Startup logs appeared because the buffer
flushed on process exit during Alembic migration.

Also kept --reload removed as it breaks stderr capture from child process.
2026-05-27 10:19:16 +03:00
bc1179722e fix: remove --reload from run.sh (breaks stderr capture), fix reason/reflect level to INFO
- run.sh: removed --reload flag from uvicorn — reload subprocess breaks
  the 2>&1 pipe and all JSON logs from superset_tools_app are lost.
  Added comment with alternative for hot-reload.
- core/logger.py: reason() and reflect() now use self.info() instead of
  self.debug() — per molecular CoT protocol these are INFO-level bonds.
  DEBUG is reserved for high-frequency loops only.
2026-05-27 10:11:36 +03:00
073a7da9ec fix: change reason() and reflect() from DEBUG to INFO level
Per molecular CoT protocol: REASON and REFLECT are primary reasoning
bonds and must be visible at INFO level in production. DEBUG is
reserved for high-frequency loops.

- reason(): self.debug()  → self.info()
- reflect(): self.debug() → self.info()
- explore(): stays at warning() (WARNING level)
- Also removed redundant logger.info() calls in lifespan (now reason()
  itself provides visible startup logging)
2026-05-27 10:09:12 +03:00
11bb4c1e26 fix: add visible startup progress logs to lifespan
- Added logger.info() calls before each startup step (encryption key,
  Alembic, init_db, admin bootstrap, scheduler, app complete)
- Previously only logger.reason() was used which logs at DEBUG level
  and is invisible in production/development at INFO log level
- This fixes 'no backend logs visible' when running via ./run.sh
2026-05-27 10:05:51 +03:00
20d8ea4d35 fix: logging audit fixes from QA
- Added missing from fastapi import status (global_exception_handler crashed)
- Moved TraceContextMiddleware to outermost (trace_id now available in log_requests)
- Enhanced global_exception_handler with query_params, client host
- Added logger.explore() in WebSocket auth except blocks (was silent pass)
- Fixed middleware registration order
2026-05-27 09:55:12 +03:00
0b55647941 fix: add global exception handler to log 500 errors
- Added @app.exception_handler(Exception) that logs full traceback via
  logger.exception() into superset_tools_app logger (visible in docker logs)
- Previously FastAPI/Starlette wrote unhandled exceptions to uvicorn.error
  logger, making 500 errors invisible in docker logs
- Added JSONResponse import for the handler
2026-05-27 09:46:14 +03:00
21e32ac4cc fix: legacy DB support + QA audit fixes
- Entrypoint: for legacy DBs, add is_admin via raw SQL then stamp head
  (instead of running full migration chain which fails on existing tables)
- Fixed admin_api_keys.py Pydantic config (dict → ConfigDict)
- Added tests/test_alembic_migrations.py (PostgreSQL-only integration tests)
- Fixed infinite recursion in _create_table_if_not_exists (QA catch)
2026-05-26 20:35:36 +03:00
e2a473aa98 fix: prevent set -e from killing entrypoint on DB detection
The python3 DB detection script exits with code 1 (empty) or 2 (legacy),
but entrypoint has set -e which kills the script on any non-zero exit.
Fixed by using '|| _db_state=$?' pattern to safely capture exit code
without triggering set -e.
2026-05-26 20:15:32 +03:00
1a57f33606 fix: handle legacy databases in entrypoint Alembic migration
Three-way detection in entrypoint:
  - alembic_version exists → normal incremental upgrade
  - no tables → fresh upgrade from scratch
  - tables exist but no alembic_version → stamp head (legacy DB created
    by create_all(), mark all migrations as current without running them)

This fixes 'relation already exists' errors when Alembic tries to CREATE
TABLE on databases that already have tables from previous deployments.
2026-05-26 19:58:31 +03:00
d870fe18d3 fix: run Alembic migrations in entrypoint before bootstrap_admin
The entrypoint was calling init_auth_db.py → init_db() + seed_permissions()
before the FastAPI startup_event (where run_alembic_migrations() lived).
Since the _ensure_*() safety net was removed, seed_permissions() failed
with 'column roles.is_admin does not exist' on databases with old schema.

Now alembic upgrade head runs directly in the entrypoint, ensuring all
migrations are applied before any DB queries.
2026-05-26 19:41:45 +03:00
7af5311449 chore: remove bundle artifact from git, add to .gitignore 2026-05-26 19:18:32 +03:00
4205618ee6 chore: eliminate all deprecation warnings from tests and linter
Warnings fixed:
- datetime.utcnow() → datetime.now(UTC) across 48+ files (src/ + tests/)
- datetime.utcnow (callback ref) → lambda: datetime.now(UTC) in model fields (18 files)
- Pydantic class Config → model_config = ConfigDict(...) (16 files)
- Pydantic .dict() → .model_dump() (8 files)
- ConfigDict(allow_population_by_field_name=True) → validate_by_name=True
- SQLAlchemy declarative_base() import path updated
- FastAPI on_event → lifespan context manager (app.py)
- Import sorting (ruff I001) auto-fixed across all files
- Fixed broken re-export chains that ruff F401 cleanup broke:
  _validate_bcp47: service.py now imports from dictionary_validation directly
  job_to_response: _job_routes.py and test imports from service_utils directly
  fetch_datasource_metadata: restored re-export in service.py
- Added missing TranslateJobService import in _job_routes.py (was deleted by F401)
- Added ConfigDict(protected_namespaces=()) for DashboardDatasetItem schema field
- pytest.ini: replaced deprecated importmode with asyncio_mode

All 440 tests pass with zero deprecation warnings.
2026-05-26 19:18:28 +03:00
eda346979b refactor: remove _ensure_*() safety net, keep only Alembic
- Simplified init_db() to only call Base.metadata.create_all() on all
  three engines — no more _ensure_*() inline additive migrations
- run_alembic_migrations() now raises on failure (no safety net to
  fall back to)
- All schema changes (add/drop/rename columns, data migrations) must
  go through Alembic. create_all() handles new tables only.

@REJECTED _ensure_*() inline migrations removed because they:
  - Duplicated Alembic logic without versioning
  - Created hidden schema drift (columns existed in DB but had no
    corresponding Alembic migration)
  - Made audits and fresh DB provisioning unreliable
2026-05-26 19:02:59 +03:00
9337a4cecd fix: add missing schema columns and Alembic model imports
- Added 4 missing columns to _ensure_translation_jobs_columns() inline
  migration: target_language_column, target_source_column,
  target_source_language_column, disable_reasoning — these were in the
  SQLAlchemy model but had no Alembic migration or _ensure_*() coverage
- Added missing api_key, assistant, clean_release model imports to
  alembic/env.py so autogenerate can see all tables
2026-05-26 19:00:04 +03:00