fix(translate,scheduler): language detection, LLM error handling, and scheduler persistence

Translation pipeline fixes (from production error log analysis):

Lang detect:
- Add "ru" to _COMMON_SOURCE_CODES for Cyrillic source detection
- Version detector cache keys (v2:) and include detector version in
  source hash — stale cache entries from old algorithm are invalidated
- Integrate _character_block_fallback into batch_detect() pipeline;
  only assign Cyrillic fallback when exactly one Cyrillic target exists
  (multiple ru/uk/be targets stay undetermined for LLM arbitration)

Batch processing:
- Case-insensitive cache language matching (cached_by_lang lookup)
- Propagate needs_review=True for undetected language rows in pre/cache path

LLM call (critical — fixes silent error hiding):
- Validate LLM row IDs against expected set; log unknown identifiers
- Retry only missing rows on incomplete response (bounded by recursion depth)
- Exhausted retries → FAILED (new _handle_incomplete_response method)
- Parse failures → FAILED instead of SKIPPED (_handle_parse_failure)
- NULL/Empty translations → FAILED via new _add_failed helper
- Source-language identity mapping preserved as TranslationLanguage entry
  (carries source_language_detected metadata that _build_insert_rows
  relies on for detected_src_lang derivation)
- finish_reason propagated to parser for truncation diagnostics

LLM parse:
- Structured incomplete-set logging with expected/received/missing counts

Target schema validation:
- Handle all non-success SQL Lab statuses (failed, timeout, error, stopped)
- Timeout gets explicit message prefix
- Route returns HTTP 502 with correct HTTPException passthrough

Scheduler persistence fix (production pickle error):
- Backup and validation APScheduler jobs now use module-level callbacks
  (execute_scheduled_backup, execute_scheduled_validation) instead of
  bound SchedulerService methods — prevents pickle failure from
  serializing TaskManager + dynamically loaded plugin classes
- Callback func identity verified via pickle round-trip smoke test

Tests:
- Update assertions: FAILED replaces SKIPPED for LLM error paths
- Restore source-language contract tests with identity-mapped values
- Add scheduler callback identity and args verification tests
- Update detector cache key tests for versioned format
- Update target schema error route test: 200→502

Orthogonal code review: MEDIUM finding (empty rec.languages when all
targets match detected source → _build_insert_rows fallback to "und")
fixed by preserving source-language TranslationLanguage entries.
This commit is contained in:
2026-07-15 13:07:41 +03:00
parent 8f4ee25415
commit 9922d7c87a
14 changed files with 283 additions and 66 deletions

View File

@@ -279,14 +279,20 @@ async def check_target_schema(
) )
try: try:
result = await validate_target_table_schema(payload, config_manager) result = await validate_target_table_schema(payload, config_manager)
if getattr(result, "error", None):
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=result.error,
)
return result return result
except HTTPException:
raise
except Exception as e: except Exception as e:
logger.explore("check_target_schema failed", logger.explore("check_target_schema failed",
extra={"src": "translate_routes", "error": str(e)}) extra={"src": "translate_routes", "error": str(e)})
return TargetSchemaValidationResponse( raise HTTPException(
table_exists=False, status_code=status.HTTP_502_BAD_GATEWAY,
error=str(e), detail=f"Failed to validate target schema: {e}",
all_present=False,
) )
# #endregion check_target_schema # #endregion check_target_schema

View File

@@ -10,14 +10,53 @@ from datetime import date, datetime, time, timedelta
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.cron import CronTrigger
from ss_tools.shared.cot_logger import seed_trace_id
from .async_job_runner import AsyncJobRunner from .async_job_runner import AsyncJobRunner
from .config_manager import ConfigManager from .config_manager import ConfigManager
from ss_tools.shared.cot_logger import seed_trace_id from .database import TASKS_DATABASE_URL, SessionLocal
from .database import SessionLocal, TASKS_DATABASE_URL
from .logger import belief_scope, logger from .logger import belief_scope, logger
# #region execute_scheduled_backup [C:3] [TYPE Function] [SEMANTICS scheduler,backup,apscheduler,persistence]
# @ingroup Core
# @BRIEF APScheduler callback for backup jobs that resolves runtime dependencies at execution time.
# @PRE env_id is a valid environment ID.
# @POST The configured backup task is triggered unless an equivalent backup is already active.
# @SIDE_EFFECT Creates a backup task and persists its execution through TaskManager.
# @RATIONALE A module-level callback with primitive arguments is required by SQLAlchemyJobStore:
# persisting a bound SchedulerService method would serialize its task manager and
# dynamically loaded plugins, which can contain duplicate module class identities.
# @REJECTED Persisting SchedulerService._trigger_backup directly was rejected — APScheduler
# attempted to pickle the service graph and failed on MaintenanceBannerPlugin.
def execute_scheduled_backup(env_id: str) -> None:
"""Resolve the scheduler service only when APScheduler invokes the job."""
from ..dependencies import get_scheduler_service
get_scheduler_service()._trigger_backup(env_id)
# #endregion execute_scheduled_backup
# #region execute_scheduled_validation [C:3] [TYPE Function] [SEMANTICS scheduler,validation,apscheduler,persistence]
# @ingroup Core
# @BRIEF APScheduler callback for validation jobs that resolves runtime dependencies at execution time.
# @PRE policy_id is a valid validation policy ID.
# @POST The configured validation policy is triggered through SchedulerService.
# @SIDE_EFFECT Creates validation tasks and schedules their execution.
# @RATIONALE Validation jobs use the same module-level callback boundary as backup jobs so the
# persistent job store never serializes SchedulerService or its dynamically loaded plugins.
def execute_scheduled_validation(policy_id: str) -> None:
"""Resolve the scheduler service only when APScheduler invokes the job."""
from ..dependencies import get_scheduler_service
get_scheduler_service()._trigger_validation(policy_id)
# #endregion execute_scheduled_validation
# #region SchedulerService [C:3] [TYPE Class] [SEMANTICS scheduler, service, apscheduler] # #region SchedulerService [C:3] [TYPE Class] [SEMANTICS scheduler, service, apscheduler]
# @defgroup Core Module group. # @defgroup Core Module group.
# @BRIEF Provides a service to manage scheduled backup tasks. # @BRIEF Provides a service to manage scheduled backup tasks.
@@ -194,6 +233,7 @@ class SchedulerService:
# @POST Job added or replaced. # @POST Job added or replaced.
# @SIDE_EFFECT APScheduler state change. # @SIDE_EFFECT APScheduler state change.
# @INVARIANT Invalid crons are skipped earlier in load_schedules. # @INVARIANT Invalid crons are skipped earlier in load_schedules.
# @NOTE The persisted callback is module-level; dependencies are resolved when the job runs.
def add_backup_job(self, env_id: str, cron_expression: str): def add_backup_job(self, env_id: str, cron_expression: str):
with belief_scope( with belief_scope(
"SchedulerService.add_backup_job", "SchedulerService.add_backup_job",
@@ -204,7 +244,7 @@ class SchedulerService:
# Validate early to give clear error (prevents garbage from old prod configs like "/15*") # Validate early to give clear error (prevents garbage from old prod configs like "/15*")
trigger = CronTrigger.from_crontab(cron_expression) trigger = CronTrigger.from_crontab(cron_expression)
self.scheduler.add_job( self.scheduler.add_job(
self._trigger_backup, execute_scheduled_backup,
trigger, trigger,
id=job_id, id=job_id,
args=[env_id], args=[env_id],
@@ -316,6 +356,7 @@ class SchedulerService:
# @POST A new APScheduler job is registered or replaced if it already exists. # @POST A new APScheduler job is registered or replaced if it already exists.
# @SIDE_EFFECT Mutates APScheduler state; calls _trigger_validation on trigger. # @SIDE_EFFECT Mutates APScheduler state; calls _trigger_validation on trigger.
# @RELATION DEPENDS_ON -> [_trigger_validation] # @RELATION DEPENDS_ON -> [_trigger_validation]
# @NOTE The persisted callback is module-level; dependencies are resolved when the job runs.
def add_validation_job(self, policy_id: str, cron_expression: str, app_timezone: str = "Europe/Moscow") -> None: def add_validation_job(self, policy_id: str, cron_expression: str, app_timezone: str = "Europe/Moscow") -> None:
with belief_scope( with belief_scope(
"SchedulerService.add_validation_job", "SchedulerService.add_validation_job",
@@ -327,7 +368,7 @@ class SchedulerService:
try: try:
tz = ZoneInfo(app_timezone) tz = ZoneInfo(app_timezone)
self.scheduler.add_job( self.scheduler.add_job(
self._trigger_validation, execute_scheduled_validation,
CronTrigger.from_crontab(cron_expression, timezone=tz), CronTrigger.from_crontab(cron_expression, timezone=tz),
id=job_id_aps, id=job_id_aps,
args=[policy_id], args=[policy_id],

View File

@@ -217,6 +217,7 @@ class BatchProcessingService:
detected_lang = row.get("_detected_lang", "und") or "und" detected_lang = row.get("_detected_lang", "und") or "und"
source_text = row.get("source_text", "") source_text = row.get("source_text", "")
is_same = row.get("_same_language") is_same = row.get("_same_language")
needs_review = str(detected_lang).lower() == "und"
# target_sql: prefer approved_translation, then first cached value, then source # target_sql: prefer approved_translation, then first cached value, then source
primary_cached = next(iter(cl.values()), "") if cl else "" primary_cached = next(iter(cl.values()), "") if cl else ""
@@ -235,15 +236,22 @@ class BatchProcessingService:
if is_same and str(lc).lower() == str(detected_lang).lower(): if is_same and str(lc).lower() == str(detected_lang).lower():
# Same language: use source text as-is (no translation needed) # Same language: use source text as-is (no translation needed)
fv = source_text fv = source_text
elif cl and lc in cl: elif cl:
fv = cl[lc] cached_by_lang = {
str(code).lower(): value for code, value in cl.items()
}
cached_value = cached_by_lang.get(str(lc).lower())
if cached_value is None:
# No translation available — skip this language.
continue
fv = cached_value
else: else:
# No translation available — skip this language # No translation available — skip this language
continue continue
self.db.add(TranslationLanguage( self.db.add(TranslationLanguage(
id=str(uuid.uuid4()), record_id=rec.id, language_code=lc, id=str(uuid.uuid4()), record_id=rec.id, language_code=lc,
source_language_detected=detected_lang, translated_value=fv, source_language_detected=detected_lang, translated_value=fv,
final_value=fv, status="translated", needs_review=False, final_value=fv, status="translated", needs_review=needs_review,
)) ))
count += 1 count += 1
return count return count

View File

@@ -42,8 +42,9 @@ for attr_name in dir(Language):
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Common source languages that appear in translation jobs (in addition to targets) # Common source languages that appear in translation jobs (in addition to targets)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
_DETECTOR_VERSION = "2"
_COMMON_SOURCE_CODES: set[str] = { _COMMON_SOURCE_CODES: set[str] = {
"en", "fr", "de", "es", "it", "pt", "pl", "uk", "en", "fr", "de", "es", "it", "pt", "pl", "ru", "uk",
"tr", "ar", "zh", "ja", "ko", "vi", "th", "nl", "tr", "ar", "zh", "ja", "ko", "vi", "th", "nl",
"sv", "da", "fi", "cs", "ro", "el", "he", "hi", "sv", "da", "fi", "cs", "ro", "el", "he", "hi",
"id", "ms", "id", "ms",
@@ -56,12 +57,12 @@ _detector_cache: dict[str, LanguageDetector] = {}
# #region _detector_cache_key [C:1] [TYPE Function] [SEMANTICS cache, key] # #region _detector_cache_key [C:1] [TYPE Function] [SEMANTICS cache, key]
# @BRIEF Build a deterministic cache key from target languages list. # @BRIEF Build a deterministic, versioned cache key from the detector version and target languages.
def _detector_cache_key(target_languages: list[str] | None) -> str: def _detector_cache_key(target_languages: list[str] | None) -> str:
"""Build a cache key from the set of target languages.""" """Build a deterministic cache key from the detector version and languages."""
if not target_languages: if not target_languages:
return "__default" return f"v{_DETECTOR_VERSION}:__default"
return ",".join(sorted(set(target_languages))) return f"v{_DETECTOR_VERSION}:" + ",".join(sorted(set(target_languages)))
# #endregion _detector_cache_key # #endregion _detector_cache_key
@@ -156,15 +157,18 @@ def _character_block_fallback(
) -> list[str]: ) -> list[str]:
"""Apply character-block heuristics for 'und' results. """Apply character-block heuristics for 'und' results.
For each 'und' result, if the target list includes a Cyrillic language (ru/uk/be) For each 'und' result, if the target list includes exactly one Cyrillic language
and the text is Cyrillic-dominant (≥35% of letter chars), assign that language. (ru/uk/be) and the text is Cyrillic-dominant (≥35% of letter chars), assign that
language. Multiple Cyrillic targets are intentionally left undetermined so the
LLM can distinguish Russian, Ukrainian, and Belarusian instead of relying on
target-list ordering.
""" """
if not target_languages: if not target_languages:
return results return results
tls_lower = [t.lower() for t in target_languages] tls_lower = [t.lower() for t in target_languages]
cyrillic_targets = [t for t in tls_lower if t in ("ru", "uk", "be")] cyrillic_targets = sorted({t for t in tls_lower if t in ("ru", "uk", "be")})
if not cyrillic_targets: if len(cyrillic_targets) != 1:
return results # no Cyrillic target → nothing to do return results # no Cyrillic target → nothing to do
for i, (text, result) in enumerate(zip(texts, results)): for i, (text, result) in enumerate(zip(texts, results)):
@@ -244,6 +248,7 @@ def batch_detect(
detector = get_detector(target_languages) detector = get_detector(target_languages)
results = [detect_language(t, detector) for t in texts] results = [detect_language(t, detector) for t in texts]
results = _character_block_fallback(texts, results, target_languages)
results = _mark_suspicious_detections_und(texts, results, target_languages) results = _mark_suspicious_detections_und(texts, results, target_languages)
return results return results
# #endregion batch_detect # #endregion batch_detect

View File

@@ -124,7 +124,12 @@ class LLMTranslationService:
logger.explore("Truncation recursion depth exceeded", {"batch_id": batch_id, "depth": _recursion_depth}) logger.explore("Truncation recursion depth exceeded", {"batch_id": batch_id, "depth": _recursion_depth})
try: try:
translations = parse_llm_response(llm_response, len(batch_rows), target_languages=target_languages) translations = parse_llm_response(
llm_response,
len(batch_rows),
target_languages=target_languages,
finish_reason=finish_reason,
)
except ValueError as e: except ValueError as e:
logger.explore( logger.explore(
f"LLM parse failure", { f"LLM parse failure", {
@@ -135,9 +140,52 @@ class LLMTranslationService:
) )
return self._handle_parse_failure(batch_rows, run_id, batch_id, retries, e) return self._handle_parse_failure(batch_rows, run_id, batch_id, retries, e)
expected_ids = {str(row.get("row_index", "")) for row in batch_rows}
valid_translations = {
row_id: data for row_id, data in translations.items()
if row_id in expected_ids
}
unknown_ids = set(translations) - expected_ids
if unknown_ids:
logger.explore(
"LLM returned unknown row identifiers",
extra={"batch_id": batch_id, "unknown_count": len(unknown_ids)},
error="unknown_row_identifier",
)
missing_rows = [
row for row in batch_rows
if str(row.get("row_index", "")) not in valid_translations
]
translated_rows = [
row for row in batch_rows
if str(row.get("row_index", "")) in valid_translations
]
result = self._create_records_from_translations( result = self._create_records_from_translations(
batch_rows, run_id, batch_id, target_languages, translations, dict_matches, retries, translated_rows, run_id, batch_id, target_languages,
valid_translations, dict_matches, retries,
) )
if missing_rows:
logger.explore(
"LLM response is incomplete; retrying missing rows",
extra={
"batch_id": batch_id,
"missing_count": len(missing_rows),
"recursion_depth": _recursion_depth,
},
error="incomplete_translation_set",
)
if _recursion_depth < MAX_RETRIES_PER_BATCH:
retry_result = await self._retry_missing_rows(
job, run_id, missing_rows, dict_matches,
batch_id, max_tokens, _recursion_depth + 1,
)
else:
retry_result = self._handle_incomplete_response(
missing_rows, run_id, batch_id, retries,
)
for key in ("successful", "failed", "skipped", "retries"):
result[key] += retry_result.get(key, 0)
logger.reason( logger.reason(
f"LLM batch complete", { f"LLM batch complete", {
"batch_id": batch_id, **result, "batch_id": batch_id, **result,
@@ -338,8 +386,9 @@ class LLMTranslationService:
row_id = str(row.get("row_index", "")) row_id = str(row.get("row_index", ""))
td = translations[row_id] td = translations[row_id]
source_text = row.get("source_text", "") source_text = row.get("source_text", "")
detected_lang = row.get("_detected_lang", "und") or "und" local_detected_lang = row.get("_detected_lang", "und") or "und"
if detected_lang == "und" and td: detected_lang = local_detected_lang
if local_detected_lang == "und" and td:
detected_lang = td.get("detected_source_language", "und") or "und" detected_lang = td.get("detected_source_language", "und") or "und"
plv = self._extract_per_lang_values(td, target_languages) plv = self._extract_per_lang_values(td, target_languages)
@@ -359,7 +408,7 @@ class LLMTranslationService:
val = source_text val = source_text
else: else:
val = plv.get(lang_code, "") val = plv.get(lang_code, "")
needs_review = (detected_lang == "und") needs_review = local_detected_lang == "und" or detected_lang == "und"
self.db.add(TranslationLanguage( self.db.add(TranslationLanguage(
id=str(uuid.uuid4()), record_id=record.id, language_code=lang_code, id=str(uuid.uuid4()), record_id=record.id, language_code=lang_code,
source_language_detected=detected_lang, translated_value=val or "", source_language_detected=detected_lang, translated_value=val or "",
@@ -406,7 +455,8 @@ class LLMTranslationService:
# #endregion _retry_missing_rows # #endregion _retry_missing_rows
# #region _handle_parse_failure [C:3] [TYPE Function] [SEMANTICS translate, llm, parse, failure] # #region _handle_parse_failure [C:3] [TYPE Function] [SEMANTICS translate, llm, parse, failure]
# @BRIEF Handle LLM parse failure — mark rows as SKIPPED. # @BRIEF Handle LLM parse failure — mark rows as FAILED.
# @POST A malformed provider response is visible as a failed row, not a policy skip.
# @SIDE_EFFECT DB writes for each row in the batch. # @SIDE_EFFECT DB writes for each row in the batch.
def _handle_parse_failure(self, batch_rows, run_id, batch_id, retries, error): def _handle_parse_failure(self, batch_rows, run_id, batch_id, retries, error):
for row in batch_rows: for row in batch_rows:
@@ -415,12 +465,29 @@ class LLMTranslationService:
source_sql=row.get("source_text", ""), target_sql=None, source_sql=row.get("source_text", ""), target_sql=None,
source_object_type="table_row", source_object_id=row.get("row_index"), source_object_type="table_row", source_object_id=row.get("row_index"),
source_object_name=row.get("source_object_name", ""), source_object_name=row.get("source_object_name", ""),
source_data=row.get("source_data"), status="SKIPPED", source_data=row.get("source_data"), status="FAILED",
error_message=f"LLM parse failure: {error}", error_message=f"LLM parse failure: {error}",
)) ))
return {"successful": 0, "failed": 0, "skipped": len(batch_rows), "retries": retries} return {"successful": 0, "failed": len(batch_rows), "skipped": 0, "retries": retries}
# #endregion _handle_parse_failure # #endregion _handle_parse_failure
# #region _handle_incomplete_response [C:3] [TYPE Function] [SEMANTICS translate, llm, failure-handling]
# @BRIEF Mark rows that remain untranslated after bounded incomplete-response retries as FAILED.
# @POST Every missing row has an explicit failure record; no LLM contract error is hidden as SKIPPED.
# @SIDE_EFFECT DB writes for each row that could not be translated.
def _handle_incomplete_response(self, batch_rows, run_id, batch_id, retries):
for row in batch_rows:
self.db.add(TranslationRecord(
id=str(uuid.uuid4()), batch_id=batch_id, run_id=run_id,
source_sql=row.get("source_text", ""), target_sql=None,
source_object_type="table_row", source_object_id=row.get("row_index"),
source_object_name=row.get("source_object_name", ""),
source_data=row.get("source_data"), status="FAILED",
error_message="LLM returned no usable translation after bounded retries",
))
return {"successful": 0, "failed": len(batch_rows), "skipped": 0, "retries": retries}
# #endregion _handle_incomplete_response
# #region _create_records_from_translations [C:3] [TYPE Function] [SEMANTICS translate, llm, persist] # #region _create_records_from_translations [C:3] [TYPE Function] [SEMANTICS translate, llm, persist]
# @BRIEF Create TranslationRecord + TranslationLanguage rows from parsed LLM translations. # @BRIEF Create TranslationRecord + TranslationLanguage rows from parsed LLM translations.
# @SIDE_EFFECT DB writes for each successfully translated row. # @SIDE_EFFECT DB writes for each successfully translated row.
@@ -432,19 +499,20 @@ class LLMTranslationService:
source_text = row.get("source_text", "") source_text = row.get("source_text", "")
# ★ Local detection (from _batch_proc._detect_languages) takes priority. # ★ Local detection (from _batch_proc._detect_languages) takes priority.
# Fallback to LLM response field for backward compatibility. # Fallback to LLM response field for backward compatibility.
detected_lang = row.get("_detected_lang", "und") or "und" local_detected_lang = row.get("_detected_lang", "und") or "und"
if detected_lang == "und" and td: detected_lang = local_detected_lang
if local_detected_lang == "und" and td:
detected_lang = td.get("detected_source_language", "und") or "und" detected_lang = td.get("detected_source_language", "und") or "und"
if td is None: if td is None:
skipped += 1 failed += 1
self._add_skipped(row, run_id, batch_id, source_text, "NULL translation") self._add_failed(row, run_id, batch_id, source_text, "NULL translation")
continue continue
plv = self._extract_per_lang_values(td, target_languages) plv = self._extract_per_lang_values(td, target_languages)
if dict_matches and source_text: if dict_matches and source_text:
_enforce_dictionary(source_text, plv, dict_matches, batch_id, row_id) _enforce_dictionary(source_text, plv, dict_matches, batch_id, row_id)
if not plv: if not plv:
skipped += 1 failed += 1
self._add_skipped(row, run_id, batch_id, source_text, "Empty translation") self._add_failed(row, run_id, batch_id, source_text, "Empty translation")
continue continue
successful += 1 successful += 1
primary = next(iter(plv.values()), "") primary = next(iter(plv.values()), "")
@@ -459,10 +527,13 @@ class LLMTranslationService:
self.db.add(record) self.db.add(record)
for lang_code in target_languages: for lang_code in target_languages:
if detected_lang != "und" and str(lang_code).lower() == str(detected_lang).lower(): if detected_lang != "und" and str(lang_code).lower() == str(detected_lang).lower():
# Source-language value is source_text (identity mapping — carries
# source_language_detected metadata that _build_insert_rows relies on
# for detected_src_lang derivation and target_source_language_column).
val = source_text val = source_text
else: else:
val = plv.get(lang_code, "") val = plv.get(lang_code, "")
needs_review = (detected_lang == "und") needs_review = local_detected_lang == "und" or detected_lang == "und"
if needs_review: if needs_review:
logger.explore("undetected language", {"record_id": row_id, "language_code": lang_code, "text": source_text[:100]}) logger.explore("undetected language", {"record_id": row_id, "language_code": lang_code, "text": source_text[:100]})
self.db.add(TranslationLanguage( self.db.add(TranslationLanguage(
@@ -506,6 +577,21 @@ class LLMTranslationService:
)) ))
# #endregion _add_skipped # #endregion _add_skipped
# #region _add_failed [C:2] [TYPE Function] [SEMANTICS translate, llm, record, failure]
# @BRIEF Add a FAILED TranslationRecord for a row with an invalid provider result.
# @POST The row is represented in run failure counts and retains an actionable reason.
# @SIDE_EFFECT DB write to translation_records.
def _add_failed(self, row, run_id, batch_id, source_text, reason):
self.db.add(TranslationRecord(
id=str(uuid.uuid4()), batch_id=batch_id, run_id=run_id,
source_sql=source_text, target_sql=None,
source_object_type="table_row", source_object_id=row.get("row_index"),
source_object_name=row.get("source_object_name", ""),
source_data=row.get("source_data"), status="FAILED",
error_message=reason,
))
# #endregion _add_failed
# #region call_llm [C:3] [TYPE Function] [SEMANTICS translate, llm, call] # #region call_llm [C:3] [TYPE Function] [SEMANTICS translate, llm, call]
# @ingroup Translate # @ingroup Translate
# @BRIEF Route to provider-specific LLM call implementation. # @BRIEF Route to provider-specific LLM call implementation.

View File

@@ -70,7 +70,15 @@ def parse_llm_response(
translations[row_id] = result translations[row_id] = result
if len(translations) < expected_count: if len(translations) < expected_count:
logger.explore(f"LLM returned fewer translations expected={expected_count} got={len(translations)}") logger.explore(
"LLM returned an incomplete translation set",
extra={
"expected_count": expected_count,
"received_count": len(translations),
"missing_count": expected_count - len(translations),
},
error="incomplete_translation_set",
)
return translations return translations
# #endregion parse_llm_response # #endregion parse_llm_response

View File

@@ -20,6 +20,7 @@ from sqlalchemy.orm import Session, joinedload
from ...core.logger import logger from ...core.logger import logger
from ...models.translate import TranslationRecord from ...models.translate import TranslationRecord
from ._lang_detect import _DETECTOR_VERSION
# #region _sanitize_url [C:1] [TYPE Function] [SEMANTICS translate, url, sanitize] # #region _sanitize_url [C:1] [TYPE Function] [SEMANTICS translate, url, sanitize]
@@ -170,6 +171,7 @@ def _compute_source_hash(
"ctx": context_data, "ctx": context_data,
"dict_hash": dict_snapshot_hash or "", "dict_hash": dict_snapshot_hash or "",
"config_hash": config_hash or "", "config_hash": config_hash or "",
"detector_version": _DETECTOR_VERSION,
}, sort_keys=True, ensure_ascii=False) }, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(payload.encode("utf-8")).hexdigest() return hashlib.sha256(payload.encode("utf-8")).hexdigest()
# #endregion _compute_source_hash # #endregion _compute_source_hash

View File

@@ -349,12 +349,19 @@ async def validate_target_table_schema(
result = await executor.execute_and_poll(sql=sql, max_polls=15, poll_interval_seconds=1.0) result = await executor.execute_and_poll(sql=sql, max_polls=15, poll_interval_seconds=1.0)
status = result.get("status", "") status = result.get("status", "")
if status == "failed": if status in {"failed", "timeout", "error", "stopped"}:
error_msg = result.get("error_message", "SQL Lab query failed") error_msg = result.get("error_message") or (
"SQL Lab schema query timed out"
if status == "timeout" else "SQL Lab query failed"
)
logger.explore("SQL Lab query failed", logger.explore("SQL Lab query failed",
extra={"payload": {"table": target_ref}, "error": error_msg}) extra={"payload": {"table": target_ref, "status": status}, "error": error_msg})
return TargetSchemaValidationResponse( return TargetSchemaValidationResponse(
table_exists=False, error=f"Superset SQL Lab error: {error_msg}", table_exists=False,
error=(
f"Superset SQL Lab timeout: {error_msg}"
if status == "timeout" else f"Superset SQL Lab error: {error_msg}"
),
expected_columns=expected, actual_columns=[], expected_columns=expected, actual_columns=[],
missing_columns=expected, extra_columns=[], all_present=False, missing_columns=expected, extra_columns=[], all_present=False,
database_name=db_name, database_backend=backend, database_name=db_name, database_backend=backend,

View File

@@ -4,7 +4,7 @@
# @TEST_EDGE: list_datasources_error -> 502 # @TEST_EDGE: list_datasources_error -> 502
# @TEST_EDGE: datasource_columns_value_error -> 400 # @TEST_EDGE: datasource_columns_value_error -> 400
# @TEST_EDGE: datasource_columns_generic_error -> 502 # @TEST_EDGE: datasource_columns_generic_error -> 502
# @TEST_EDGE: check_target_schema_error -> 200 with error field # @TEST_EDGE: check_target_schema_error -> 502 with error detail
# @TEST_EDGE: list_jobs_value_error -> 400 # @TEST_EDGE: list_jobs_value_error -> 400
# @TEST_EDGE: create_job_value_error -> 422 # @TEST_EDGE: create_job_value_error -> 422
# @TEST_EDGE: update_job_value_error -> 404 # @TEST_EDGE: update_job_value_error -> 404
@@ -206,7 +206,7 @@ class TestCheckTargetSchema:
assert "target_database_id" in resp.text assert "target_database_id" in resp.text
def test_check_target_schema_exception_handled(self): def test_check_target_schema_exception_handled(self):
"""Exception in validate_target_table_schema returns 200 with error field.""" """Exception in validate_target_table_schema returns 502."""
with patch( with patch(
"src.api.routes.translate._job_routes.validate_target_table_schema", "src.api.routes.translate._job_routes.validate_target_table_schema",
side_effect=RuntimeError("Connection refused"), side_effect=RuntimeError("Connection refused"),
@@ -217,10 +217,8 @@ class TestCheckTargetSchema:
"target_database_id": "db-1", "target_database_id": "db-1",
"target_table": "my_table", "target_table": "my_table",
}) })
assert resp.status_code == 200 assert resp.status_code == 502
data = resp.json() assert "Connection refused" in resp.text
assert data["table_exists"] is False
assert data["error"] is not None
# ============================================================================= # =============================================================================

View File

@@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patch
from lingua import LanguageDetectorBuilder from lingua import LanguageDetectorBuilder
from src.plugins.translate._lang_detect import ( from src.plugins.translate._lang_detect import (
_DETECTOR_VERSION,
_detector_cache_key, _detector_cache_key,
build_detector, build_detector,
get_detector, get_detector,
@@ -26,22 +27,22 @@ class TestDetectorCacheKey:
"""_detector_cache_key.""" """_detector_cache_key."""
def test_none(self): def test_none(self):
"""None returns '__default'.""" """None returns a versioned default key."""
assert _detector_cache_key(None) == "__default" assert _detector_cache_key(None) == f"v{_DETECTOR_VERSION}:__default"
def test_empty_list(self): def test_empty_list(self):
"""Empty list returns '__default'.""" """Empty list returns a versioned default key."""
assert _detector_cache_key([]) == "__default" assert _detector_cache_key([]) == f"v{_DETECTOR_VERSION}:__default"
def test_sorted_key(self): def test_sorted_key(self):
"""Languages are sorted for deterministic key.""" """Languages are sorted for deterministic key."""
key = _detector_cache_key(["fr", "en", "de"]) key = _detector_cache_key(["fr", "en", "de"])
assert key == "de,en,fr" assert key == f"v{_DETECTOR_VERSION}:de,en,fr"
def test_duplicates(self): def test_duplicates(self):
"""Duplicates are removed.""" """Duplicates are removed."""
key = _detector_cache_key(["en", "en", "fr"]) key = _detector_cache_key(["en", "en", "fr"])
assert key == "en,fr" assert key == f"v{_DETECTOR_VERSION}:en,fr"
class TestBuildDetector: class TestBuildDetector:

View File

@@ -3,7 +3,7 @@
# @RELATION BINDS_TO -> [LLMTranslationService] # @RELATION BINDS_TO -> [LLMTranslationService]
# @TEST_EDGE: batch_empty -> Handled gracefully # @TEST_EDGE: batch_empty -> Handled gracefully
# @TEST_EDGE: llm_all_retries_exhausted -> Returns failure counts # @TEST_EDGE: llm_all_retries_exhausted -> Returns failure counts
# @TEST_EDGE: parse_failure -> Returns skipped counts # @TEST_EDGE: parse_failure -> Returns failed counts
# @TEST_EDGE: truncation_recovery -> Recovers partial rows # @TEST_EDGE: truncation_recovery -> Recovers partial rows
# @TEST_EDGE: no_provider -> Raises ValueError # @TEST_EDGE: no_provider -> Raises ValueError
import json import json
@@ -218,7 +218,7 @@ class TestCallLlmForBatch:
dict_matches=[], batch_id="batch-1", dict_matches=[], batch_id="batch-1",
) )
assert result["successful"] == 0 assert result["successful"] == 0
assert result["skipped"] == 1 assert result["failed"] == 1
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_successful_translation(self, db_with_run): async def test_successful_translation(self, db_with_run):
@@ -376,15 +376,15 @@ class TestHandleLlmFailure:
class TestHandleParseFailure: class TestHandleParseFailure:
"""Verify _handle_parse_failure.""" """Verify _handle_parse_failure."""
def test_all_rows_marked_skipped(self, db_with_run): def test_all_rows_marked_failed(self, db_with_run):
session, run_id = db_with_run session, run_id = db_with_run
svc = LLMTranslationService(session) svc = LLMTranslationService(session)
rows = _batch_rows(2) rows = _batch_rows(2)
result = svc._handle_parse_failure(rows, run_id, "batch-1", 2, ValueError("Bad parse")) result = svc._handle_parse_failure(rows, run_id, "batch-1", 2, ValueError("Bad parse"))
assert result["skipped"] == 2 assert result["failed"] == 2
records = session.query(TranslationRecord).all() records = session.query(TranslationRecord).all()
assert len(records) == 2 assert len(records) == 2
assert all(r.status == "SKIPPED" for r in records) assert all(r.status == "FAILED" for r in records)
class TestCreateRecordsFromTranslations: class TestCreateRecordsFromTranslations:
@@ -405,7 +405,7 @@ class TestCreateRecordsFromTranslations:
langs = session.query(TranslationLanguage).all() langs = session.query(TranslationLanguage).all()
assert len(langs) == 1 assert len(langs) == 1
def test_null_translation_skipped(self, db_with_run): def test_null_translation_failed(self, db_with_run):
session, run_id = db_with_run session, run_id = db_with_run
svc = LLMTranslationService(session) svc = LLMTranslationService(session)
rows = _batch_rows(1) rows = _batch_rows(1)
@@ -413,9 +413,9 @@ class TestCreateRecordsFromTranslations:
result = svc._create_records_from_translations( result = svc._create_records_from_translations(
rows, run_id, "batch-1", ["fr"], translations, [], 0, rows, run_id, "batch-1", ["fr"], translations, [], 0,
) )
assert result["skipped"] == 1 assert result["failed"] == 1
def test_empty_plv_skipped(self, db_with_run): def test_empty_plv_failed(self, db_with_run):
session, run_id = db_with_run session, run_id = db_with_run
svc = LLMTranslationService(session) svc = LLMTranslationService(session)
rows = _batch_rows(1) rows = _batch_rows(1)
@@ -423,7 +423,7 @@ class TestCreateRecordsFromTranslations:
result = svc._create_records_from_translations( result = svc._create_records_from_translations(
rows, run_id, "batch-1", ["fr"], translations, [], 0, rows, run_id, "batch-1", ["fr"], translations, [], 0,
) )
assert result["skipped"] == 1 assert result["failed"] == 1
def test_with_dict_enforcement(self, db_with_run): def test_with_dict_enforcement(self, db_with_run):
session, run_id = db_with_run session, run_id = db_with_run

View File

@@ -66,7 +66,7 @@ class TestCreateRecordsUndetectedLang:
assert langs[0].needs_review is True assert langs[0].needs_review is True
def test_detected_lang_same_as_target_lang_identity(self, db_with_run): def test_detected_lang_same_as_target_lang_identity(self, db_with_run):
"""When detected_lang matches target language code, value is source_text (identity mapping).""" """When detected_lang matches a target, source-language gets identity mapping (source_text)."""
session, run_id = db_with_run session, run_id = db_with_run
svc = LLMTranslationService(session) svc = LLMTranslationService(session)
rows = _batch_rows(1, detected_lang="fr") rows = _batch_rows(1, detected_lang="fr")
@@ -81,8 +81,14 @@ class TestCreateRecordsUndetectedLang:
assert "fr" in lang_codes assert "fr" in lang_codes
assert "de" in lang_codes assert "de" in lang_codes
fr_lang = [l for l in langs if l.language_code == "fr"][0] fr_lang = [l for l in langs if l.language_code == "fr"][0]
# fr translation value should be source_text (not the LLM response "Bonjour") de_lang = [l for l in langs if l.language_code == "de"][0]
# Source-language entry carries source_text for _build_insert_rows metadata
assert fr_lang.translated_value == "Hello world 0" assert fr_lang.translated_value == "Hello world 0"
assert fr_lang.final_value == "Hello world 0"
assert fr_lang.source_language_detected == "fr"
# Translated language entry carries LLM response
assert de_lang.translated_value == "Hallo"
assert de_lang.final_value == "Hallo"
def test_detected_lang_fallback_to_llm_response(self, db_with_run): def test_detected_lang_fallback_to_llm_response(self, db_with_run):
"""When _detected_lang is 'und', fall back to LLM response field.""" """When _detected_lang is 'und', fall back to LLM response field."""

View File

@@ -222,9 +222,9 @@ class TestCreateRecordsLanguageArbitration:
"""Regression tests for LLM-assisted source-language detection.""" """Regression tests for LLM-assisted source-language detection."""
# #region test_llm_detected_same_language_creates_skip_marker [C:2] [TYPE Function] # #region test_llm_detected_same_language_creates_skip_marker [C:2] [TYPE Function]
# @BRIEF und local detection + LLM-detected same target creates marker language entry. # @BRIEF und local detection + LLM-detected same target creates identity-mapped language entry.
def test_llm_detected_same_language_creates_skip_marker(self): def test_llm_detected_same_language_creates_skip_marker(self):
"""When LLM detects ru for target ru, insert stage must skip translation row.""" """When LLM detects ru for target ru, source-language gets identity mapping (source_text)."""
db = MagicMock() db = MagicMock()
service = LLMTranslationService(db) service = LLMTranslationService(db)
rows = [{ rows = [{

View File

@@ -269,8 +269,8 @@ def test_load_schedules_loads_validation_policies():
# #region test_trigger_validation_creates_tasks [C:1] [TYPE Function] # #region test_trigger_validation_creates_tasks [C:1] [TYPE Function]
def test_trigger_validation_creates_tasks(): def test_trigger_validation_creates_tasks():
"""Verify _trigger_validation creates TaskManager tasks for each dashboard.""" """Verify _trigger_validation creates TaskManager tasks for each dashboard."""
from src.core.scheduler import SchedulerService
from src.core.async_job_runner import AsyncJobRunner from src.core.async_job_runner import AsyncJobRunner
from src.core.scheduler import SchedulerService
sched = _start_scheduler() sched = _start_scheduler()
try: try:
@@ -534,6 +534,7 @@ def test_reload_validation_policy_removes_job_when_policy_gone():
def test_scheduler_init_uses_persistent_jobstore(): def test_scheduler_init_uses_persistent_jobstore():
"""SchedulerService.__init__ configures SQLAlchemyJobStore (inspired by APS production recommendations).""" """SchedulerService.__init__ configures SQLAlchemyJobStore (inspired by APS production recommendations)."""
from unittest.mock import patch from unittest.mock import patch
from src.core.scheduler import SchedulerService from src.core.scheduler import SchedulerService
cfg = _make_mock_config_manager() cfg = _make_mock_config_manager()
@@ -559,6 +560,54 @@ def test_scheduler_init_uses_persistent_jobstore():
# #endregion test_scheduler_init_uses_persistent_jobstore # #endregion test_scheduler_init_uses_persistent_jobstore
# #region test_backup_job_uses_module_level_callback [C:1] [TYPE Function]
def test_backup_job_uses_module_level_callback():
"""Persistent backup jobs must not capture SchedulerService's object graph."""
from src.core.scheduler import SchedulerService, execute_scheduled_backup
sched = _start_scheduler()
try:
svc = SchedulerService.__new__(SchedulerService)
svc.task_manager = _make_mock_task_manager()
svc.config_manager = _make_mock_config_manager()
svc.scheduler = sched
svc.runner = MagicMock()
svc.add_backup_job("env-persist", "0 3 * * *")
job = sched.get_job("backup_env-persist")
assert job is not None
assert job.func is execute_scheduled_backup
assert job.args == ("env-persist",)
finally:
_stop_scheduler(sched)
# #endregion test_backup_job_uses_module_level_callback
# #region test_validation_job_uses_module_level_callback [C:1] [TYPE Function]
def test_validation_job_uses_module_level_callback():
"""Persistent validation jobs must not capture SchedulerService's object graph."""
from src.core.scheduler import SchedulerService, execute_scheduled_validation
sched = _start_scheduler()
try:
svc = SchedulerService.__new__(SchedulerService)
svc.task_manager = _make_mock_task_manager()
svc.config_manager = _make_mock_config_manager()
svc.scheduler = sched
svc.runner = MagicMock()
svc.add_validation_job("policy-persist", "0 3 * * *")
job = sched.get_job("validation_policy-persist")
assert job is not None
assert job.func is execute_scheduled_validation
assert job.args == ("policy-persist",)
finally:
_stop_scheduler(sched)
# #endregion test_validation_job_uses_module_level_callback
# #region test_load_schedules_differential_prune [C:1] [TYPE Function] # #region test_load_schedules_differential_prune [C:1] [TYPE Function]
def test_load_schedules_differential_prune(): def test_load_schedules_differential_prune():
"""load_schedules now does differential sync instead of remove_all (uses jobstore).""" """load_schedules now does differential sync instead of remove_all (uses jobstore)."""