# Implementation Plan: LLM Table Translation Service **Branch**: `028-llm-datasource-supeset` | **Date**: 2026-05-08 | **Spec**: [spec.md](./spec.md) **Input**: Feature specification from `/specs/028-llm-datasource-supeset/spec.md` (updated 2026-05-14 with multi-language & correction optimization) ## Summary Implement an LLM-powered table translation service as a new backend plugin (`TranslationPlugin`) with companion API routes, ORM models, Pydantic schemas, and Svelte frontend components. The service reads rows from a Superset datasource (translation column + context columns), auto-detects source language per row via LLM, sends batches to a configured LLM provider for ALL target languages simultaneously (multi-target in single structured JSON response), with optional per-batch filtered multilingual terminology dictionary context (language-pair-aware). Generates safe PostgreSQL INSERT/UPSERT SQL, submits to Superset via `/api/v1/sqllab/execute/` with status polling. Supporting capabilities: multilingual terminology dictionaries (source_language + target_language per entry), configurable preview (1-100 rows), inline correction from any run result with dictionary submission, bulk find-and-replace, scheduled execution via APScheduler (new-key-only with baseline_expired fallback), structured event logging with per-language MetricSnapshot persistence, RBAC-gated access control, and 90-day retention with metric continuity. **Total planned modules**: 31 contracts across backend (Python/FastAPI) and frontend (Svelte 5/SvelteKit). **Complexity distribution**: 2× C5 (orchestrator, event-log), 9× C4 (preview, execute, dictionary, scheduler, SQL-gen, routes, correction), 13× C3 (models, schemas, components, services), 7× C2 (helpers, new models). ## Technical Context **Language/Version**: Python 3.13+ (backend), JavaScript/TypeScript (frontend Svelte 5) **Primary Dependencies**: FastAPI 0.115+, SQLAlchemy 2.0+, APScheduler 3.x, Pydantic v2 (backend); SvelteKit 2.x, Svelte 5.43+, Vite 7.x, Tailwind CSS 3.x (frontend) **Storage**: PostgreSQL 16 (shared with existing ss-tools schema) **Testing**: pytest 8.x + pytest-asyncio (backend); vitest 4.x + @testing-library/svelte 5.x (frontend) **Target Platform**: Linux server (Docker Compose: backend + frontend + PostgreSQL) **Project Type**: web application — FastAPI REST + WebSocket backend, SvelteKit SPA frontend **Performance Goals**: Preview of 10 rows within 30s (LLM-dependent); INSERT generation <5s for 1000 rows; schedule trigger precision ±60s; event recording <10s after occurrence **Constraints**: RBAC enforcement via access-control matrix; dictionary per-batch filtering (case-insensitive, word-boundary-aware); 90-day detailed data retention with MetricSnapshot persistence; plugin lifecycle compatible with `PluginBase`; dialect-aware SQL generation (PostgreSQL/Greenplum, ClickHouse supported for MVP); snapshot isolation for in-progress runs; structured JSON LLM output required **Scale/Scope**: Tens of thousands of rows per run; dictionaries of any size; 50 concurrent users; 5–10 active translation jobs per deployment ## Constitution Check *GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* | Principle | Status | Evidence | |-----------|--------|----------| | **I. Plugin Architecture** | ✅ PASS | Feature implemented as a new plugin inheriting from `PluginBase` (`backend/src/plugins/translate/`), consistent with existing `llm_analysis`, `git`, `storage` plugin pattern. | | **II. API-First Design** | ✅ PASS | All operations exposed via REST endpoints under `/api/translate/` (jobs, dictionaries, runs, schedules, history) and WebSocket for run progress. Follows existing FastAPI route conventions. | | **III. Test-First** | ✅ PASS | Acceptance criteria per user story defined in spec; test strategy in research.md covers unit (pytest), integration (API + DB), and component (vitest + Svelte Testing Library) layers. | | **IV. RBAC & Security** | ✅ PASS | Granular permissions (`translate.job.*`, `translate.dictionary.*`, `translate.schedule.manage`, `translate.history.view`) via existing RBAC model. API keys encrypted via `EncryptionManager`. PII masking for LLM-facing context per existing patterns. | | **V. Observability & Retention** | ✅ PASS | Structured Translation Events (FR-046), per-job metrics (FR-047), notification integration (FR-048), 90-day retention with pruning (FR-049). C4+ flows instrumented with `belief_scope`/`reason`/`reflect`/`explore` markers. | | **Semantic Protocol Compliance** | ✅ PASS | All planned modules assigned `@COMPLEXITY` 1–5 with appropriate tag density per GRACE complexity scale (C1: anchor only, C2: +BRIEF, C3: +RELATION, C4: +PRE/POST/SIDE_EFFECT, C5: +DATA_CONTRACT/INVARIANT/RATIONALE/REJECTED). `@RATIONALE`/`@REJECTED` reserved for C5 contracts only. Canonical `@RELATION PREDICATE -> TARGET_ID` syntax. Anchor format: `#region`/`#endregion` for Python, ``/`` for Svelte markup. | | **Fractal Limit (INV_7)** | ✅ PASS | Planned modules kept under 400 lines each. No planned contract exceeds 150 lines or CC>10. Decomposition strategy documented in contracts/modules.md. | **Gate Result**: ✅ ALL PASS — no blocking constitutional or semantic conflicts. ## Project Structure ### Documentation (this feature) ```text specs/028-llm-datasource-supeset/ ├── plan.md # This file ├── research.md # Phase 0 output ├── data-model.md # Phase 1 output ├── quickstart.md # Phase 1 output ├── contracts/ # Phase 1 output │ └── modules.md # Semantic contract design ├── spec.md # Feature specification ├── ux_reference.md # Interaction reference └── checklists/ └── requirements.md # Quality validation ``` ### Source Code (repository root) ```text backend/ ├── src/ │ ├── api/routes/ │ │ └── translate.py # New: translation REST endpoints │ ├── core/ │ │ ├── scheduler.py # Existing: APScheduler (extend for translation schedules) │ │ └── superset_client/ # Existing: Superset API client (reuse) │ ├── models/ │ │ └── translate.py # New: SQLAlchemy ORM models │ ├── plugins/ │ │ └── translate/ # New: TranslationPlugin │ │ ├── __init__.py │ │ ├── plugin.py # Plugin entry (inherits PluginBase) │ │ ├── orchestrator.py # Run lifecycle orchestration (C5) │ │ ├── preview.py # Preview engine (C4) │ │ ├── executor.py # Batch execution + INSERT gen (C4) │ │ ├── dictionary.py # Dictionary CRUD + filtering (C4) │ │ ├── sql_generator.py # INSERT/UPSERT SQL generation (C3) │ │ ├── scheduler.py # Schedule management (C4) │ │ ├── events.py # Structured event logging (C5) │ │ ├── metrics.py # Per-job metrics aggregation (C3) │ │ └── __tests__/ # Plugin-level tests │ ├── schemas/ │ │ └── translate.py # New: Pydantic request/response schemas │ └── services/ │ ├── llm_provider.py # Existing: LLM provider management (reuse) │ └── llm_prompt_templates.py # Existing: prompt rendering (reuse) └── tests/ # Integration tests frontend/ ├── src/ │ ├── routes/ │ │ └── translate/ # New: SvelteKit route │ │ ├── +page.svelte # Translation job list │ │ ├── [id]/ │ │ │ └── +page.svelte # Job config + preview + run │ │ ├── dictionaries/ │ │ │ ├── +page.svelte # Dictionary list │ │ │ └── [id]/ │ │ │ └── +page.svelte # Dictionary editor │ │ └── history/ │ │ └── +page.svelte # Run history │ └── lib/ │ ├── components/ │ │ └── translate/ # New: reusable translation components │ │ ├── TranslationJobConfig.svelte │ │ ├── TranslationPreview.svelte │ │ ├── TranslationRunProgress.svelte │ │ ├── TranslationRunResult.svelte │ │ ├── DictionaryEditor.svelte │ │ ├── TermCorrectionPopup.svelte │ │ ├── ScheduleConfig.svelte │ │ └── BulkCorrectionSidebar.svelte │ ├── stores/ │ │ └── translate.js # New: Svelte 5 rune stores │ └── api/ │ └── translate.js # New: API client module ``` ## Semantic Contract Guidance - All planned contracts follow GRACE-Poly v2.6 protocol with `#region`/`#endregion` anchors (or `[DEF:...]`/`[/DEF:...]` for backward compatibility in docs). - Python backend uses `# #region`/`# #endregion` comment-anchor syntax. - Svelte components use ``/`` in markup and `// #region`/`// #endregion` in script blocks. - Complexity assignments follow strict tag density per GRACE complexity scale (detailed in `contracts/modules.md`). - C4+ Python modules instrumented with `belief_scope()` + `reason()`/`reflect()`/`explore()` markers. - C5 contracts carry `@RATIONALE` and `@REJECTED` decision memory (C1-C4 MUST NOT have these tags). - `@RELATION` targets reference existing contracts where applicable (e.g., `[LLMProviderService:Module]`, `[SchedulerService:Class]`, `[SupersetClient:Module]`, `[NotificationService:Module]`). ## Complexity Tracking No constitutional violations detected. All complexity assignments are justified within the semantic protocol's complexity scale: | Contract | Complexity | Justification | |----------|-----------|---------------| | `TranslationOrchestrator` | C5 | Stateful lifecycle with PRE/POST, multi-step coordination, decision memory for retry/concurrency policies; updated for multi-target orchestration | | `TranslationScheduler` | C4 | Stateful schedule CRUD with APScheduler integration, conflict detection | | `TranslationEventLog` | C5 | Immutable event log with retention enforcement, audit invariants, decision memory for pruning strategy | | `TranslationPreview` | C4 | Stateful multi-language preview with LLM calls, configurable sample size, approve/edit/reject lifecycle | | `TranslationExecutor` | C4 | Multi-language batch execution, per-language TranslationLanguage entries, per-language statistics | | `DictionaryManager` | C4 | Multilingual CRUD with import/export, language-pair-aware batch filtering, conflict resolution | | `InlineCorrectionService` | C3 | Inline correction with dictionary submission, origin tracking | | `BulkFindReplaceService` | C3 | Find-and-replace across run results, regex support, multi-language awareness | | `TranslationLanguage` | C1 | DTO for per-language translation storage | | `TranslationRunLanguageStats` | C1 | DTO for per-language statistics aggregation | | `CorrectionCell` (Svelte) | C3 | Inline editable cell with submit-to-dictionary UX state machine | | `BulkReplaceModal` (Svelte) | C3 | Find-and-replace modal with preview table | | `ContextAwarePromptBuilder` | C3 | Context-aware dictionary prompt construction with Jaccard similarity, priority flagging, context truncation | | `InlineCorrectionService` (extended) | C3 | Context capture from source rows, context editing, usage notes, context_source tagging | | Other Svelte components | C3 | Existing components updated with per-language columns, configurable preview, context display |