feat(translate,scheduler,trace): new-key-only mode, stale PENDING protection, trace_id propagation
Translations: - FR-045: new-key-only execution mode — translate only rows with unseen keys - Compare source row keys against TranslationRecord.source_data from last succeeded run - Baseline expired (>90 days) fallback to full mode with baseline_expired event - run_noop early return when zero new keys (skip LLM + SQL) Scheduler reliability: - Stale PENDING protection: runs older than 1h auto-marked FAILED, no longer block schedule - load_schedules() reloads active translation schedules from DB on restart - add_translation_job/remove_translation_job register/unregister with APScheduler - execution_mode column on translation_schedules with additive DB migration Automation view: - GET /settings/automation/translation-schedules endpoint - Translation schedules displayed on Automation page below validation policies Trace propagation: - seed_trace_id() in all background entry points: TaskManager._run_task/_flusher_loop, SchedulerService._trigger_backup, websocket_endpoint, IdMappingService, all standalone scripts Migrations: - dictionary_entries: origin_run_id, origin_row_key, origin_user_id - translation_schedules: execution_mode Tests: - 3 new test modules (22 tests): core_scheduler, executor_filter, scheduler_execution+guard - Fix pre-existing translate test isolation (conftest.py) - Fix test_list_runs_filter_status parameter
This commit is contained in:
@@ -44,6 +44,7 @@ async def get_schedule(
|
||||
"cron_expression": schedule.cron_expression,
|
||||
"timezone": schedule.timezone,
|
||||
"is_active": schedule.is_active,
|
||||
"execution_mode": schedule.execution_mode,
|
||||
"last_run_at": schedule.last_run_at.isoformat() if schedule.last_run_at else None,
|
||||
"next_run_at": schedule.next_run_at.isoformat() if schedule.next_run_at else None,
|
||||
"created_by": schedule.created_by,
|
||||
@@ -77,12 +78,14 @@ async def set_schedule(
|
||||
existing = db.query(TranslationSchedule).filter(
|
||||
TranslationSchedule.job_id == job_id
|
||||
).first()
|
||||
execution_mode = getattr(payload, 'execution_mode', 'full')
|
||||
if existing:
|
||||
schedule = scheduler.update_schedule(
|
||||
job_id,
|
||||
cron_expression=payload.cron_expression,
|
||||
timezone_str=payload.timezone,
|
||||
is_active=payload.is_active,
|
||||
execution_mode=execution_mode,
|
||||
)
|
||||
else:
|
||||
schedule = scheduler.create_schedule(
|
||||
@@ -90,6 +93,7 @@ async def set_schedule(
|
||||
cron_expression=payload.cron_expression,
|
||||
timezone=payload.timezone,
|
||||
is_active=payload.is_active,
|
||||
execution_mode=execution_mode,
|
||||
)
|
||||
# Register with APScheduler via SchedulerService
|
||||
from ....dependencies import get_scheduler_service
|
||||
@@ -99,6 +103,7 @@ async def set_schedule(
|
||||
job_id=job_id,
|
||||
cron_expression=schedule.cron_expression,
|
||||
timezone=schedule.timezone,
|
||||
execution_mode=schedule.execution_mode,
|
||||
)
|
||||
return {
|
||||
"id": schedule.id,
|
||||
@@ -106,6 +111,7 @@ async def set_schedule(
|
||||
"cron_expression": schedule.cron_expression,
|
||||
"timezone": schedule.timezone,
|
||||
"is_active": schedule.is_active,
|
||||
"execution_mode": schedule.execution_mode,
|
||||
"last_run_at": schedule.last_run_at.isoformat() if schedule.last_run_at else None,
|
||||
"created_by": schedule.created_by,
|
||||
"created_at": schedule.created_at.isoformat() if schedule.created_at else None,
|
||||
@@ -140,6 +146,7 @@ async def enable_schedule(
|
||||
job_id=job_id,
|
||||
cron_expression=schedule.cron_expression,
|
||||
timezone=schedule.timezone,
|
||||
execution_mode=schedule.execution_mode,
|
||||
)
|
||||
return {"status": "enabled", "job_id": job_id}
|
||||
except ValueError as e:
|
||||
|
||||
@@ -272,6 +272,7 @@ async def websocket_endpoint(
|
||||
source: Filter logs by source component (e.g., "plugin", "superset_api")
|
||||
level: Filter logs by minimum level (DEBUG, INFO, WARNING, ERROR)
|
||||
"""
|
||||
seed_trace_id()
|
||||
with belief_scope("websocket_endpoint", f"task_id={task_id}"):
|
||||
await websocket.accept()
|
||||
source_filter = source.lower() if source else None
|
||||
|
||||
@@ -579,6 +579,96 @@ def _ensure_dataset_review_session_columns(bind_engine):
|
||||
# #endregion _ensure_dataset_review_session_columns
|
||||
|
||||
|
||||
# #region _ensure_translation_schedules_columns [C:3] [TYPE Function]
|
||||
# @BRIEF Applies additive schema upgrades for translation_schedules table.
|
||||
# @PRE: bind_engine points to application database.
|
||||
# @POST: Missing columns are added without data loss.
|
||||
# @RELATION DEPENDS_ON -> [engine]
|
||||
def _ensure_translation_schedules_columns(bind_engine):
|
||||
with belief_scope("_ensure_translation_schedules_columns"):
|
||||
table_name = "translation_schedules"
|
||||
inspector = inspect(bind_engine)
|
||||
if table_name not in inspector.get_table_names():
|
||||
return
|
||||
|
||||
existing_columns = {
|
||||
str(column.get("name") or "").strip()
|
||||
for column in inspector.get_columns(table_name)
|
||||
}
|
||||
|
||||
alter_statements = []
|
||||
if "execution_mode" not in existing_columns:
|
||||
alter_statements.append(
|
||||
"ALTER TABLE translation_schedules "
|
||||
"ADD COLUMN execution_mode VARCHAR NOT NULL DEFAULT 'full'"
|
||||
)
|
||||
|
||||
if not alter_statements:
|
||||
return
|
||||
|
||||
try:
|
||||
with bind_engine.begin() as connection:
|
||||
for statement in alter_statements:
|
||||
connection.execute(text(statement))
|
||||
except Exception as migration_error:
|
||||
logger.explore(
|
||||
"TranslationSchedule additive migration failed",
|
||||
extra={"src": "database", "error": str(migration_error)},
|
||||
)
|
||||
|
||||
|
||||
# #endregion _ensure_translation_schedules_columns
|
||||
|
||||
|
||||
# #region _ensure_dictionary_entries_columns [C:3] [TYPE Function]
|
||||
# @BRIEF Additive migration for dictionary_entries origin tracking columns.
|
||||
# @RELATION DEPENDS_ON -> [engine]
|
||||
def _ensure_dictionary_entries_columns(bind_engine):
|
||||
with belief_scope("_ensure_dictionary_entries_columns"):
|
||||
table_name = "dictionary_entries"
|
||||
inspector = inspect(bind_engine)
|
||||
if table_name not in inspector.get_table_names():
|
||||
return
|
||||
|
||||
existing_columns = {
|
||||
str(column.get("name") or "").strip()
|
||||
for column in inspector.get_columns(table_name)
|
||||
}
|
||||
|
||||
alter_statements = []
|
||||
if "origin_run_id" not in existing_columns:
|
||||
alter_statements.append(
|
||||
"ALTER TABLE dictionary_entries "
|
||||
"ADD COLUMN origin_run_id VARCHAR"
|
||||
)
|
||||
if "origin_row_key" not in existing_columns:
|
||||
alter_statements.append(
|
||||
"ALTER TABLE dictionary_entries "
|
||||
"ADD COLUMN origin_row_key VARCHAR"
|
||||
)
|
||||
if "origin_user_id" not in existing_columns:
|
||||
alter_statements.append(
|
||||
"ALTER TABLE dictionary_entries "
|
||||
"ADD COLUMN origin_user_id VARCHAR"
|
||||
)
|
||||
|
||||
if not alter_statements:
|
||||
return
|
||||
|
||||
try:
|
||||
with bind_engine.begin() as connection:
|
||||
for statement in alter_statements:
|
||||
connection.execute(text(statement))
|
||||
except Exception as migration_error:
|
||||
logger.explore(
|
||||
"DictionaryEntry additive migration failed",
|
||||
extra={"src": "database", "error": str(migration_error)},
|
||||
)
|
||||
|
||||
|
||||
# #endregion _ensure_dictionary_entries_columns
|
||||
|
||||
|
||||
# #region init_db [C:3] [TYPE Function]
|
||||
# @BRIEF Initializes the database by creating all tables.
|
||||
# @PRE: engine, tasks_engine and auth_engine are initialized.
|
||||
@@ -587,6 +677,7 @@ def _ensure_dataset_review_session_columns(bind_engine):
|
||||
# @RELATION CALLS -> [ensure_connection_configs_table]
|
||||
# @RELATION CALLS -> [_ensure_filter_source_enum_values]
|
||||
# @RELATION CALLS -> [_ensure_dataset_review_session_columns]
|
||||
# @RELATION CALLS -> [_ensure_dictionary_entries_columns]
|
||||
def init_db():
|
||||
with belief_scope("init_db"):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -601,6 +692,8 @@ def init_db():
|
||||
_ensure_filter_source_enum_values(engine)
|
||||
_ensure_dataset_review_session_columns(engine)
|
||||
_ensure_translation_jobs_columns(engine)
|
||||
_ensure_translation_schedules_columns(engine)
|
||||
_ensure_dictionary_entries_columns(engine)
|
||||
|
||||
|
||||
# #endregion init_db
|
||||
|
||||
@@ -18,6 +18,7 @@ from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from src.models.mapping import ResourceMapping, ResourceType
|
||||
from src.core.logger import logger, belief_scope
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
# #region IdMappingService [C:5] [TYPE Class]
|
||||
# @BRIEF Service handling the cataloging and retrieval of remote Superset Integer IDs.
|
||||
# @PRE: db_session is an active SQLAlchemy Session bound to mapping tables.
|
||||
@@ -65,6 +66,7 @@ class IdMappingService:
|
||||
"[IdMappingService.start_scheduler][Reflect] Removed existing sync job."
|
||||
)
|
||||
def sync_all():
|
||||
seed_trace_id()
|
||||
for env_id in environments:
|
||||
client = superset_client_factory(env_id)
|
||||
if client:
|
||||
@@ -98,6 +100,7 @@ class IdMappingService:
|
||||
Polls the Superset APIs for the target environment and updates the local mapping table.
|
||||
If incremental=True, only fetches items changed since the max last_synced_at date.
|
||||
"""
|
||||
seed_trace_id()
|
||||
with belief_scope("IdMappingService.sync_environment"):
|
||||
logger.reason(
|
||||
f"Starting sync for environment {environment_id}",
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from .logger import logger, belief_scope
|
||||
from .cot_logger import seed_trace_id
|
||||
from .config_manager import ConfigManager
|
||||
from .database import SessionLocal
|
||||
import asyncio
|
||||
@@ -45,10 +46,11 @@ class SchedulerService:
|
||||
self.scheduler.shutdown()
|
||||
logger.info("Scheduler stopped.")
|
||||
# #endregion stop
|
||||
# #region load_schedules [TYPE Function]
|
||||
# @PURPOSE: Loads backup schedules from configuration and registers them.
|
||||
# @PRE: config_manager must have valid configuration.
|
||||
# @POST: All enabled backup jobs are added to the scheduler.
|
||||
# #region load_schedules [C:4] [TYPE Function] [SEMANTICS scheduler,backup,translation,apscheduler]
|
||||
# @BRIEF Load backup and active translation schedules from config and DB, re-registering all jobs.
|
||||
# @PRE config_manager must have valid configuration; database is accessible.
|
||||
# @POST All enabled backup jobs and active translation schedules are re-registered in APScheduler.
|
||||
# @SIDE_EFFECT Removes all existing APScheduler jobs; queries translation_schedules table; registers APScheduler jobs for translation.
|
||||
def load_schedules(self):
|
||||
with belief_scope("SchedulerService.load_schedules"):
|
||||
# Clear existing jobs
|
||||
@@ -57,6 +59,31 @@ class SchedulerService:
|
||||
for env in config.environments:
|
||||
if env.backup_schedule and env.backup_schedule.enabled:
|
||||
self.add_backup_job(env.id, env.backup_schedule.cron_expression)
|
||||
# Re-register active translation schedules from the database
|
||||
try:
|
||||
from ..models.translate import TranslationSchedule
|
||||
db = SessionLocal()
|
||||
try:
|
||||
active_schedules = (
|
||||
db.query(TranslationSchedule)
|
||||
.filter(TranslationSchedule.is_active == True)
|
||||
.all()
|
||||
)
|
||||
for sched in active_schedules:
|
||||
self.add_translation_job(
|
||||
schedule_id=sched.id,
|
||||
job_id=sched.job_id,
|
||||
cron_expression=sched.cron_expression,
|
||||
timezone=sched.timezone,
|
||||
execution_mode=getattr(sched, 'execution_mode', 'full'),
|
||||
)
|
||||
if active_schedules:
|
||||
logger.reason(f"Loaded {len(active_schedules)} active translation schedule(s)")
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
logger.explore("Failed to load translation schedules on startup",
|
||||
extra={"error": str(e)})
|
||||
# #endregion load_schedules
|
||||
# #region add_backup_job [TYPE Function]
|
||||
# @PURPOSE: Adds a scheduled backup job for an environment.
|
||||
@@ -91,7 +118,7 @@ class SchedulerService:
|
||||
# @SIDE_EFFECT Mutates APScheduler state; calls execute_scheduled_translation on trigger.
|
||||
# @RELATION DEPENDS_ON -> [execute_scheduled_translation]
|
||||
# @RELATION DEPENDS_ON -> [SessionLocal]
|
||||
def add_translation_job(self, schedule_id: str, job_id: str, cron_expression: str, timezone: str = "UTC"):
|
||||
def add_translation_job(self, schedule_id: str, job_id: str, cron_expression: str, timezone: str = "UTC", execution_mode: str = "full"):
|
||||
with belief_scope(
|
||||
"SchedulerService.add_translation_job",
|
||||
f"schedule_id={schedule_id}, job_id={job_id}, cron={cron_expression}",
|
||||
@@ -106,7 +133,7 @@ class SchedulerService:
|
||||
execute_scheduled_translation,
|
||||
CronTrigger.from_crontab(cron_expression, timezone=tz),
|
||||
id=job_id_aps,
|
||||
args=[schedule_id, job_id, SessionLocal, self.config_manager],
|
||||
args=[schedule_id, job_id, SessionLocal, self.config_manager, execution_mode],
|
||||
replace_existing=True,
|
||||
)
|
||||
logger.reason(
|
||||
@@ -141,6 +168,7 @@ class SchedulerService:
|
||||
# @POST: A new backup task is created in the task manager if not already running.
|
||||
# @PARAM: env_id (str) - The ID of the environment.
|
||||
def _trigger_backup(self, env_id: str):
|
||||
seed_trace_id()
|
||||
with belief_scope("SchedulerService._trigger_backup", f"env_id={env_id}"):
|
||||
logger.info(f"Triggering scheduled backup for environment {env_id}")
|
||||
# Check if a backup is already running for this environment
|
||||
|
||||
@@ -34,6 +34,7 @@ from .models import Task, TaskStatus, LogEntry, LogFilter, LogStats
|
||||
from .persistence import TaskPersistenceService, TaskLogPersistenceService
|
||||
from .context import TaskContext
|
||||
from ..logger import logger, belief_scope, should_log_task_level
|
||||
from ..cot_logger import seed_trace_id
|
||||
# #region TaskManager [C:5] [TYPE Class] [SEMANTICS task, manager, lifecycle, execution, state]
|
||||
# @BRIEF Manages the lifecycle of tasks, including their creation, execution, and state tracking.
|
||||
# @LAYER: Core
|
||||
@@ -138,6 +139,7 @@ class TaskManager:
|
||||
# @RELATION: [DEPENDS_ON] ->[EventBus]
|
||||
def _flusher_loop(self):
|
||||
"""Background thread that flushes log buffer to database."""
|
||||
seed_trace_id() # seed trace_id for the daemon flusher thread
|
||||
while not self._flusher_stop_event.is_set():
|
||||
self._flush_logs()
|
||||
self._flusher_stop_event.wait(self.LOG_FLUSH_INTERVAL)
|
||||
@@ -150,6 +152,7 @@ class TaskManager:
|
||||
# @RELATION: [DEPENDS_ON] ->[EventBus]
|
||||
def _flush_logs(self):
|
||||
"""Flush all buffered logs to the database."""
|
||||
seed_trace_id()
|
||||
with self._log_buffer_lock:
|
||||
task_ids = list(self._log_buffer.keys())
|
||||
for task_id in task_ids:
|
||||
@@ -232,6 +235,7 @@ class TaskManager:
|
||||
# @RELATION: [DEPENDS_ON] ->[TaskContext]
|
||||
# @RELATION: [DEPENDS_ON] ->[EventBus]
|
||||
async def _run_task(self, task_id: str):
|
||||
seed_trace_id()
|
||||
with belief_scope("TaskManager._run_task", f"task_id={task_id}"):
|
||||
task = self.tasks[task_id]
|
||||
plugin = self.plugin_loader.get_plugin(task.plugin_id)
|
||||
|
||||
@@ -239,6 +239,7 @@ class TranslationSchedule(Base):
|
||||
is_active = Column(Boolean, default=True)
|
||||
last_run_at = Column(DateTime, nullable=True)
|
||||
next_run_at = Column(DateTime, nullable=True)
|
||||
execution_mode = Column(String, nullable=False, default="full", comment="full, new_key_only")
|
||||
created_by = Column(String, nullable=True)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -40,6 +40,7 @@ from .preview import DEFAULT_EXECUTION_PROMPT_TEMPLATE
|
||||
# #region MAX_RETRIES_PER_BATCH [TYPE Constant]
|
||||
# @BRIEF Maximum number of retries for a single batch before marking it failed.
|
||||
MAX_RETRIES_PER_BATCH = 3
|
||||
# #endregion MAX_RETRIES_PER_BATCH
|
||||
|
||||
|
||||
# #region TranslationExecutor [C:4] [TYPE Class]
|
||||
@@ -97,6 +98,20 @@ class TranslationExecutor:
|
||||
self.db.flush()
|
||||
return run
|
||||
|
||||
# Apply new-key-only filtering for scheduled runs
|
||||
if run.trigger_type == "new_key_only":
|
||||
source_rows = self._filter_new_keys(job, run.id, source_rows)
|
||||
if not source_rows:
|
||||
logger.reason("run_noop — no new rows to translate", {
|
||||
"job_id": job.id, "run_id": run.id,
|
||||
})
|
||||
run.status = "COMPLETED"
|
||||
run.insert_status = "skipped"
|
||||
run.total_records = 0
|
||||
run.completed_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
return
|
||||
|
||||
total_rows = len(source_rows)
|
||||
run.total_records = total_rows
|
||||
|
||||
@@ -303,6 +318,74 @@ class TranslationExecutor:
|
||||
return source_rows
|
||||
# endregion _fetch_source_rows
|
||||
|
||||
# region _filter_new_keys [TYPE Function]
|
||||
# @PURPOSE: Filter source rows to only include those with keys absent from the last successful run.
|
||||
# @PRE: job and run are persisted; source_rows is a list of dicts with source_data containing key columns.
|
||||
# @POST: Returns filtered list of source rows with only new keys. Logs skip count.
|
||||
# @SIDE_EFFECT: Queries TranslationRecord from previous runs; no writes.
|
||||
def _filter_new_keys(self, job, run_id: str, source_rows: list) -> list:
|
||||
with belief_scope("TranslationExecutor._filter_new_keys"):
|
||||
# Find most recent COMPLETED run with successful insert for this job
|
||||
prev_run = (
|
||||
self.db.query(TranslationRun)
|
||||
.filter(
|
||||
TranslationRun.job_id == job.id,
|
||||
TranslationRun.status == "COMPLETED",
|
||||
TranslationRun.insert_status == "succeeded",
|
||||
TranslationRun.id != run_id,
|
||||
)
|
||||
.order_by(TranslationRun.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
if not prev_run:
|
||||
logger.reason("No prior successful run — all keys treated as new", {
|
||||
"job_id": job.id,
|
||||
})
|
||||
return source_rows
|
||||
|
||||
# Get successful records from that run
|
||||
prev_records = (
|
||||
self.db.query(TranslationRecord)
|
||||
.filter(
|
||||
TranslationRecord.run_id == prev_run.id,
|
||||
TranslationRecord.status == "SUCCESS",
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not prev_records:
|
||||
return source_rows
|
||||
|
||||
# Build set of already-translated composite keys
|
||||
key_cols = job.target_key_cols or job.source_key_cols or []
|
||||
if not key_cols:
|
||||
logger.explore("No key columns configured — skipping new-key-only filter",
|
||||
{"job_id": job.id})
|
||||
return source_rows
|
||||
existing_keys = set()
|
||||
for rec in prev_records:
|
||||
sd = rec.source_data or {}
|
||||
key_tuple = tuple(str(sd.get(k, "")) for k in key_cols)
|
||||
existing_keys.add(key_tuple)
|
||||
|
||||
# Filter: keep only rows whose keys are NOT in the existing set
|
||||
filtered = []
|
||||
skipped = 0
|
||||
for row in source_rows:
|
||||
sd = row.get("source_data", {}) or {}
|
||||
key_tuple = tuple(str(sd.get(k, "")) for k in key_cols)
|
||||
if key_tuple not in existing_keys:
|
||||
filtered.append(row)
|
||||
else:
|
||||
skipped += 1
|
||||
|
||||
logger.reason(f"New-key-only filter: {len(source_rows)} total → {len(filtered)} new, {skipped} skipped", {
|
||||
"job_id": job.id,
|
||||
"prev_run_id": prev_run.id,
|
||||
"key_cols": key_cols,
|
||||
})
|
||||
return filtered
|
||||
# endregion _filter_new_keys
|
||||
|
||||
# region _extract_chart_data_rows [TYPE Function]
|
||||
# @PURPOSE: Extract data rows from Superset chart data API response.
|
||||
# @POST: Returns list of dicts with column-value pairs.
|
||||
@@ -763,4 +846,3 @@ class TranslationExecutor:
|
||||
|
||||
# #endregion TranslationExecutor
|
||||
# #endregion TranslationExecutor
|
||||
# #endregion TranslationExecutor
|
||||
|
||||
@@ -19,6 +19,7 @@ from typing import Any, Dict, List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...core.logger import logger, belief_scope
|
||||
from ...core.cot_logger import seed_trace_id
|
||||
from ...core.config_manager import ConfigManager
|
||||
from ...models.translate import TranslationSchedule, TranslationJob, TranslationRun
|
||||
from .events import TranslationEventLog
|
||||
@@ -44,6 +45,7 @@ class TranslationScheduler:
|
||||
cron_expression: str,
|
||||
timezone: str = "UTC",
|
||||
is_active: bool = True,
|
||||
execution_mode: str = "full",
|
||||
) -> TranslationSchedule:
|
||||
with belief_scope("TranslationScheduler.create_schedule"):
|
||||
# Verify job exists
|
||||
@@ -57,6 +59,7 @@ class TranslationScheduler:
|
||||
cron_expression=cron_expression,
|
||||
timezone=timezone,
|
||||
is_active=is_active,
|
||||
execution_mode=execution_mode,
|
||||
created_by=self.current_user,
|
||||
)
|
||||
self.db.add(schedule)
|
||||
@@ -88,6 +91,7 @@ class TranslationScheduler:
|
||||
cron_expression: Optional[str] = None,
|
||||
timezone_str: Optional[str] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
execution_mode: Optional[str] = None,
|
||||
) -> TranslationSchedule:
|
||||
with belief_scope("TranslationScheduler.update_schedule"):
|
||||
schedule = self.db.query(TranslationSchedule).filter(
|
||||
@@ -102,6 +106,8 @@ class TranslationScheduler:
|
||||
schedule.timezone = timezone_str
|
||||
if is_active is not None:
|
||||
schedule.is_active = is_active
|
||||
if execution_mode is not None:
|
||||
schedule.execution_mode = execution_mode
|
||||
schedule.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
self.db.refresh(schedule)
|
||||
@@ -245,8 +251,10 @@ def execute_scheduled_translation(
|
||||
job_id: str,
|
||||
db_session_maker,
|
||||
config_manager: ConfigManager,
|
||||
execution_mode: str = "full",
|
||||
) -> None:
|
||||
"""APScheduler job callback for scheduled translations."""
|
||||
seed_trace_id()
|
||||
db: Session = db_session_maker()
|
||||
try:
|
||||
with belief_scope("execute_scheduled_translation"):
|
||||
@@ -265,26 +273,57 @@ def execute_scheduled_translation(
|
||||
})
|
||||
|
||||
# Concurrency check: max 1 pending/running run per job
|
||||
STALE_THRESHOLD = timedelta(hours=1)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
active_run = (
|
||||
db.query(TranslationRun)
|
||||
.filter(
|
||||
TranslationRun.job_id == job_id,
|
||||
TranslationRun.status.in_(["PENDING", "RUNNING"]),
|
||||
)
|
||||
.order_by(TranslationRun.created_at.asc()) # oldest first
|
||||
.first()
|
||||
)
|
||||
if active_run:
|
||||
logger.explore("Skipping scheduled run — concurrent run in progress", {
|
||||
"job_id": job_id,
|
||||
"existing_run_id": active_run.id,
|
||||
})
|
||||
event_log = TranslationEventLog(db)
|
||||
event_log.log_event(
|
||||
job_id=job_id,
|
||||
event_type="RUN_STARTED",
|
||||
payload={"reason": "skipped_concurrent", "existing_run_id": active_run.id},
|
||||
is_stale = (
|
||||
active_run.status == "PENDING"
|
||||
and active_run.created_at
|
||||
and (now - active_run.created_at) > STALE_THRESHOLD
|
||||
)
|
||||
return
|
||||
if is_stale:
|
||||
# Mark ALL stale PENDING runs as FAILED
|
||||
stale_runs = (
|
||||
db.query(TranslationRun)
|
||||
.filter(
|
||||
TranslationRun.job_id == job_id,
|
||||
TranslationRun.status == "PENDING",
|
||||
TranslationRun.created_at < (now - STALE_THRESHOLD),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for sr in stale_runs:
|
||||
sr.status = "FAILED"
|
||||
sr.error_message = "Stale: concurrency deadlock — marked by scheduled trigger"
|
||||
sr.completed_at = now
|
||||
db.commit()
|
||||
logger.explore(f"Cleared {len(stale_runs)} stale PENDING run(s), proceeding with scheduled trigger", {
|
||||
"job_id": job_id,
|
||||
"stale_run_ids": [sr.id for sr in stale_runs],
|
||||
})
|
||||
# Proceed to execute the scheduled run (do NOT return)
|
||||
else:
|
||||
logger.explore("Skipping scheduled run — concurrent run in progress", {
|
||||
"job_id": job_id,
|
||||
"existing_run_id": active_run.id,
|
||||
})
|
||||
event_log = TranslationEventLog(db)
|
||||
event_log.log_event(
|
||||
job_id=job_id,
|
||||
event_type="RUN_STARTED",
|
||||
payload={"reason": "skipped_concurrent", "existing_run_id": active_run.id},
|
||||
)
|
||||
return
|
||||
|
||||
# Check baseline expiry
|
||||
baseline_expired = False
|
||||
@@ -315,7 +354,17 @@ def execute_scheduled_translation(
|
||||
job_id=job_id,
|
||||
is_scheduled=True,
|
||||
)
|
||||
run.trigger_type = "scheduled"
|
||||
|
||||
# Determine trigger type based on execution_mode and baseline expiry
|
||||
if execution_mode == "new_key_only" and not baseline_expired:
|
||||
run.trigger_type = "new_key_only"
|
||||
elif execution_mode == "new_key_only" and baseline_expired:
|
||||
logger.reason("Baseline expired — falling back to full translation", {
|
||||
"job_id": job_id, "schedule_id": schedule_id, "age_days": age.days,
|
||||
})
|
||||
run.trigger_type = "scheduled"
|
||||
else:
|
||||
run.trigger_type = "scheduled"
|
||||
db.flush()
|
||||
|
||||
if baseline_expired:
|
||||
|
||||
@@ -102,6 +102,7 @@ class TranslationScheduleItem(BaseModel):
|
||||
cron_expression: str
|
||||
timezone: str
|
||||
is_active: bool
|
||||
execution_mode: str = "full"
|
||||
last_run_at: Optional[datetime] = None
|
||||
next_run_at: Optional[datetime] = None
|
||||
created_by: Optional[str] = None
|
||||
|
||||
@@ -313,6 +313,7 @@ class ScheduleConfig(BaseModel):
|
||||
cron_expression: str = Field(..., description="Cron expression for scheduling (e.g. '0 2 * * *')")
|
||||
timezone: str = Field("UTC", description="Timezone for the cron schedule (e.g. 'UTC', 'Europe/Moscow')")
|
||||
is_active: bool = True
|
||||
execution_mode: str = Field("full", description="Translation execution mode: 'full' or 'new_key_only'")
|
||||
# #endregion ScheduleConfig
|
||||
|
||||
|
||||
@@ -324,6 +325,7 @@ class ScheduleResponse(BaseModel):
|
||||
cron_expression: str
|
||||
timezone: str
|
||||
is_active: bool
|
||||
execution_mode: str = "full"
|
||||
last_run_at: Optional[datetime] = None
|
||||
next_run_at: Optional[datetime] = None
|
||||
created_by: Optional[str] = None
|
||||
|
||||
@@ -10,6 +10,7 @@ import json
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from ..core.cot_logger import seed_trace_id
|
||||
from ..models.clean_release import CandidateArtifact, ReleaseCandidate
|
||||
from ..services.clean_release.approval_service import (
|
||||
approve_candidate,
|
||||
@@ -468,6 +469,7 @@ def run_revoke(args: argparse.Namespace) -> int:
|
||||
# #region main [TYPE Function]
|
||||
# @BRIEF CLI entrypoint for clean release commands.
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
seed_trace_id()
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ BACKEND_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, "..", ".."))
|
||||
if BACKEND_ROOT not in sys.path:
|
||||
sys.path.insert(0, BACKEND_ROOT)
|
||||
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
from src.models.clean_release import (
|
||||
CandidateArtifact,
|
||||
CheckFinalStatus,
|
||||
@@ -662,6 +663,7 @@ def tui_main(stdscr: curses.window):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
seed_trace_id()
|
||||
# TUI requires interactive terminal; headless mode must use CLI/API flow.
|
||||
if not sys.stdout.isatty():
|
||||
print(
|
||||
|
||||
@@ -19,6 +19,7 @@ from src.core.database import AuthSessionLocal, init_db
|
||||
from src.core.auth.security import get_password_hash
|
||||
from src.models.auth import User, Role
|
||||
from src.core.logger import logger, belief_scope
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
|
||||
|
||||
# #region create_admin [TYPE Function]
|
||||
@@ -27,6 +28,7 @@ from src.core.logger import logger, belief_scope
|
||||
# @POST: Admin user exists in auth.db.
|
||||
#
|
||||
def create_admin(username, password, email=None):
|
||||
seed_trace_id()
|
||||
with belief_scope("create_admin"):
|
||||
db = AuthSessionLocal()
|
||||
try:
|
||||
|
||||
@@ -17,6 +17,7 @@ sys.path.append(str(Path(__file__).parent.parent.parent))
|
||||
from src.core.database import init_db
|
||||
from src.core.encryption_key import ensure_encryption_key
|
||||
from src.core.logger import logger, belief_scope
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
from src.scripts.seed_permissions import seed_permissions
|
||||
|
||||
|
||||
@@ -27,6 +28,7 @@ from src.scripts.seed_permissions import seed_permissions
|
||||
# @RELATION CALLS -> init_db
|
||||
# @RELATION CALLS -> seed_permissions
|
||||
def run_init():
|
||||
seed_trace_id()
|
||||
with belief_scope("init_auth_db"):
|
||||
logger.info("Initializing authentication database...")
|
||||
try:
|
||||
|
||||
@@ -21,6 +21,7 @@ from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from src.core.logger import belief_scope, logger
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
|
||||
|
||||
# #region Constants [TYPE Section]
|
||||
@@ -327,6 +328,7 @@ def _migrate_tasks_and_logs(engine, sqlite_conn: sqlite3.Connection) -> Dict[str
|
||||
def run_migration(
|
||||
sqlite_path: Path, target_url: str, legacy_config_path: Optional[Path]
|
||||
) -> Dict[str, int]:
|
||||
seed_trace_id()
|
||||
with belief_scope("run_migration"):
|
||||
logger.reason(
|
||||
f"sqlite={sqlite_path} target={target_url}",
|
||||
|
||||
@@ -19,6 +19,7 @@ from src.core.database import AuthSessionLocal
|
||||
from src.models.auth import Permission, Role
|
||||
from src.core.auth.repository import AuthRepository
|
||||
from src.core.logger import logger, belief_scope
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
|
||||
# #region INITIAL_PERMISSIONS [C:3] [TYPE Constant]
|
||||
# @BRIEF Canonical bootstrap permission tuples seeded into auth storage.
|
||||
@@ -66,6 +67,7 @@ INITIAL_PERMISSIONS = [
|
||||
# @RELATION DEPENDS_ON -> AuthRepository
|
||||
# @RELATION DEPENDS_ON -> INITIAL_PERMISSIONS
|
||||
def seed_permissions():
|
||||
seed_trace_id()
|
||||
with belief_scope("seed_permissions"):
|
||||
db = AuthSessionLocal()
|
||||
try:
|
||||
|
||||
@@ -19,6 +19,7 @@ sys.path.append(str(Path(__file__).parent.parent.parent))
|
||||
from src.core.config_manager import ConfigManager
|
||||
from src.core.config_models import Environment
|
||||
from src.core.logger import belief_scope, logger
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
from src.core.superset_client import SupersetClient
|
||||
|
||||
|
||||
@@ -255,6 +256,7 @@ def _build_chart_template_pool(
|
||||
# @POST: Returns execution statistics dictionary.
|
||||
# @SIDE_EFFECT: Creates objects in Superset environments.
|
||||
def seed_superset_load_data(args: argparse.Namespace) -> Dict:
|
||||
seed_trace_id()
|
||||
rng = random.Random(args.seed)
|
||||
env_map = _resolve_target_envs(args.envs)
|
||||
|
||||
@@ -381,6 +383,7 @@ def seed_superset_load_data(args: argparse.Namespace) -> Dict:
|
||||
# @PRE: Command line arguments are valid.
|
||||
# @POST: Prints summary and exits with non-zero status on failure.
|
||||
def main() -> None:
|
||||
seed_trace_id()
|
||||
with belief_scope("seed_superset_load_test.main"):
|
||||
args = _parse_args()
|
||||
result = seed_superset_load_data(args)
|
||||
|
||||
@@ -18,10 +18,12 @@ sys.path.append(str(Path(__file__).parent.parent.parent))
|
||||
from src.core.superset_client import SupersetClient
|
||||
from src.core.config_manager import ConfigManager
|
||||
from src.core.logger import logger
|
||||
from src.core.cot_logger import seed_trace_id
|
||||
|
||||
|
||||
def test_dashboard_dataset_relations():
|
||||
"""Test fetching dataset-to-dashboard relationships."""
|
||||
seed_trace_id()
|
||||
|
||||
# Load environment from existing config
|
||||
config_manager = ConfigManager()
|
||||
|
||||
Reference in New Issue
Block a user