88from sqlalchemy .orm import Session
99from sqlalchemy .exc import OperationalError
1010
11- from .db import check_db_connection , get_db , init_db , count_active_temp_files , update_status
11+ from .db import check_db_connection , get_db , init_db , update_status
1212from .models import MediaUpload , ProcessingStatus
1313from .input_validator import validate_input
1414from .temp_manager import (
15- ensure_temp_dir , write_to_temp , delete_from_temp , cleanup_on_startup , TEMP_FILE_CAP
15+ ensure_temp_dir , write_to_temp , delete_from_temp , cleanup_on_startup
1616)
1717from .ml_stub import run_ml
1818from .minio_client import ensure_bucket , upload_to_minio
@@ -47,9 +47,7 @@ def init_db_with_retry(max_retries=10, delay=3):
4747
4848@app .on_event ("startup" )
4949def on_startup ():
50- # 🔁 retry until DB is ready
5150 init_db_with_retry ()
52-
5351 ensure_temp_dir ()
5452 ensure_bucket ()
5553
@@ -192,9 +190,7 @@ async def upload_file(file: UploadFile = File(...), db: Session = Depends(get_db
192190 processed_at = datetime .utcnow (),
193191 )
194192
195- delete_from_temp (temp_path )
196-
197- # Step 5 — trigger agents (unchanged for now)
193+ # Step 5 — trigger agents FIRST
198194 def _run_agents ():
199195 try :
200196 requests .post (
@@ -207,6 +203,9 @@ def _run_agents():
207203
208204 threading .Thread (target = _run_agents , daemon = True ).start ()
209205
206+ # ✅ NOW safe to delete temp file
207+ delete_from_temp (temp_path )
208+
210209 logger .info (
211210 '{"message": "Upload pipeline complete", "id": %s, "filename": "%s"}' ,
212211 record_id ,
0 commit comments