Files
resolutionflow/backend/app/services/psa_retry_scheduler.py
chihlasm a48660700a fix: background jobs and lifespan must use BYPASSRLS sessions
All code that runs outside a request context (APScheduler jobs,
lifespan startup) has no app.current_account_id set, so the
app-role session returns 0 rows from every RLS-protected table.

Changed to _admin_session_factory (BYPASSRLS) in:
- knowledge_flywheel_scheduler.py — queries ai_sessions
- psa_retry_scheduler.py — queries psa_post_log
- retention_cleanup.py — queries assistant_chats
- scheduler.py (_fire_maintenance_schedule, _cleanup_expired_ai_conversations)
- main.py (archive_stale_ai_sessions, _process_notification_retries,
  load_all_schedules at startup)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 03:44:23 +00:00

53 lines
1.8 KiB
Python

"""Background scheduler for retrying failed PSA documentation pushes.
Runs every 5 minutes via APScheduler, picks up PsaPostLog entries
with status='pending_retry' and next_retry_at <= now.
"""
import logging
from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.admin_database import _admin_session_factory as async_session_maker
from app.models.psa_post_log import PsaPostLog
from app.services.psa_documentation_service import retry_failed_push
logger = logging.getLogger(__name__)
async def process_pending_retries() -> None:
"""Process all pending PSA push retries that are due."""
async with async_session_maker() as db:
try:
result = await db.execute(
select(PsaPostLog)
.where(
PsaPostLog.status == "pending_retry",
PsaPostLog.next_retry_at <= datetime.now(timezone.utc),
PsaPostLog.retry_count < 3,
)
.limit(20) # Process in batches
)
entries = result.scalars().all()
if not entries:
return
logger.info("Processing %d pending PSA push retries", len(entries))
for entry in entries:
success = await retry_failed_push(entry, db)
if success:
logger.info("PSA retry succeeded for log %s", entry.id)
else:
logger.warning(
"PSA retry %d/%d failed for log %s",
entry.retry_count, 3, entry.id,
)
await db.commit()
except Exception as e:
logger.error("PSA retry scheduler error: %s", e)
await db.rollback()