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

@@ -3,7 +3,7 @@
# @RELATION BINDS_TO -> [LLMTranslationService]
# @TEST_EDGE: batch_empty -> Handled gracefully
# @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: no_provider -> Raises ValueError
import json
@@ -218,7 +218,7 @@ class TestCallLlmForBatch:
dict_matches=[], batch_id="batch-1",
)
assert result["successful"] == 0
assert result["skipped"] == 1
assert result["failed"] == 1
@pytest.mark.asyncio
async def test_successful_translation(self, db_with_run):
@@ -376,15 +376,15 @@ class TestHandleLlmFailure:
class TestHandleParseFailure:
"""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
svc = LLMTranslationService(session)
rows = _batch_rows(2)
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()
assert len(records) == 2
assert all(r.status == "SKIPPED" for r in records)
assert all(r.status == "FAILED" for r in records)
class TestCreateRecordsFromTranslations:
@@ -405,7 +405,7 @@ class TestCreateRecordsFromTranslations:
langs = session.query(TranslationLanguage).all()
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
svc = LLMTranslationService(session)
rows = _batch_rows(1)
@@ -413,9 +413,9 @@ class TestCreateRecordsFromTranslations:
result = svc._create_records_from_translations(
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
svc = LLMTranslationService(session)
rows = _batch_rows(1)
@@ -423,7 +423,7 @@ class TestCreateRecordsFromTranslations:
result = svc._create_records_from_translations(
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):
session, run_id = db_with_run