File size: 24,165 Bytes
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c23f275
 
 
 
 
b3b36f7
c23f275
 
 
 
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643c0d4
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa191f1
b3b36f7
 
 
aa191f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
31a340a
aa191f1
 
b3b36f7
 
aa191f1
b3b36f7
 
 
 
 
 
e57e9d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e57e9d1
 
c23f275
 
e57e9d1
c23f275
e57e9d1
b3b36f7
 
 
 
e125b13
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e125b13
b3b36f7
 
 
 
 
 
 
 
 
 
 
e57e9d1
 
 
 
 
 
db6c149
e57e9d1
 
bb3710e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e57e9d1
 
 
 
 
 
 
 
 
 
 
 
 
bb3710e
e57e9d1
 
 
 
 
 
 
 
b3b36f7
c23f275
b3b36f7
c23f275
 
 
 
167e1a2
 
 
c23f275
 
f678e15
e125b13
 
c23f275
 
 
 
 
 
 
f678e15
167e1a2
c23f275
167e1a2
 
 
c23f275
167e1a2
 
 
 
 
b3b36f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
"""
Worker tasks for arq.

This module defines the tasks that the worker executes.
The main task is `run_pipeline` which orchestrates the entire pipeline.

Faz 2: Integrated news_raw/news_processed pipeline with proper
       commit boundaries, metrics tracking, and degraded mode handling.
"""

import logging
import os
import socket
import uuid
from datetime import datetime, timezone
from typing import Any, Optional

from sqlalchemy.orm import Session

# These imports will be updated as we refactor
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.db import SessionLocal, init_db, get_db_type
from app.settings import get_settings
from app.models import PipelineRunMetrics
from adapters.db.lock import (
    PIPELINE_LOCK_KEY,
    try_acquire_lock,
    release_lock,
    write_lock_visibility,
    clear_lock_visibility,
)

logger = logging.getLogger(__name__)


# =============================================================================
# Helper functions for metrics tracking
# =============================================================================

def create_run_metrics(
    session: Session,
    run_id: str,
    started_at: datetime,
) -> PipelineRunMetrics:
    """Create initial pipeline_run_metrics record."""
    metrics = PipelineRunMetrics(
        run_id=run_id,
        run_started_at=started_at,
        status="running",
    )
    session.add(metrics)
    session.flush()
    return metrics


def update_run_metrics(
    session: Session,
    run_id: str,
    **kwargs,
) -> None:
    """Update pipeline_run_metrics with new values."""
    metrics = session.query(PipelineRunMetrics).filter(
        PipelineRunMetrics.run_id == run_id
    ).first()
    
    if metrics:
        for key, value in kwargs.items():
            if hasattr(metrics, key):
                setattr(metrics, key, value)
        session.flush()


def finalize_run_metrics(
    session: Session,
    run_id: str,
    status: str,
    quality_state: str = "ok",
    error_message: Optional[str] = None,
) -> None:
    """Finalize run metrics with completion status."""
    completed_at = datetime.now(timezone.utc)
    
    metrics = session.query(PipelineRunMetrics).filter(
        PipelineRunMetrics.run_id == run_id
    ).first()
    
    if metrics:
        metrics.run_completed_at = completed_at
        metrics.status = status
        metrics.quality_state = quality_state
        if metrics.run_started_at:
            metrics.duration_seconds = (completed_at - metrics.run_started_at).total_seconds()
        if error_message:
            metrics.error_message = error_message
        session.flush()


# =============================================================================
# Main pipeline task
# =============================================================================

async def run_pipeline(
    ctx: dict,
    run_id: str,
    train_model: bool = False,
    trigger_source: str = "unknown",
    enqueued_at: str = None,
) -> dict:
    """
    Main pipeline task - executed by arq worker.
    
    This is the ONLY entrypoint for pipeline execution.
    
    Faz 2 Flow:
        Stage 1a: News ingestion β†’ news_raw
        Stage 1b: Raw processing β†’ news_processed
        Stage 1c: Cut-off calculation
        Stage 1d: Price ingestion
        Stage 2: Sentiment scoring
        Stage 3: Sentiment aggregation
        Stage 3.5: FinBERT embedding extraction
        Stage 4: XGBoost training (optional)
        Stage 5: XGBoost snapshot
        Stage 5.5: TFT-ASRO inference (downloads checkpoint from HF Hub)
        Stage 6: Commentary generation

    Note: TFT-ASRO full training is handled exclusively by the weekly
    tft-training.yml GitHub workflow. The daily pipeline only runs inference.

    Args:
        ctx: arq context (contains redis connection)
        run_id: Unique identifier for this run
        train_model: Whether to train the XGBoost model
        trigger_source: Where the trigger came from (cron, manual, api)
        enqueued_at: ISO timestamp when job was enqueued
        
    Returns:
        dict with run results
    """
    started_at = datetime.now(timezone.utc)
    holder_id = f"{socket.gethostname()}:{os.getpid()}"
    run_uuid = uuid.UUID(run_id) if isinstance(run_id, str) else run_id
    
    logger.info(f"[run_id={run_id}] Pipeline starting: trigger={trigger_source}, train_model={train_model}")
    
    # Initialize database
    init_db()
    
    # Get a dedicated session for this pipeline run
    # IMPORTANT: This session holds the advisory lock
    session: Session = SessionLocal()
    quality_state = "ok"
    result = {}
    
    try:
        # 0. Create run metrics record
        create_run_metrics(session, run_id, started_at)
        session.commit()
        
        # 1. Acquire distributed lock
        if not try_acquire_lock(session, PIPELINE_LOCK_KEY):
            logger.warning(f"[run_id={run_id}] Pipeline skipped: lock held by another process")
            finalize_run_metrics(session, run_id, status="skipped_locked", quality_state="skipped")
            session.commit()
            return {
                "run_id": run_id,
                "status": "skipped_locked",
                "message": "Another pipeline is running",
            }
        
        # Write lock visibility (best-effort)
        write_lock_visibility(session, PIPELINE_LOCK_KEY, run_id, holder_id)
        session.commit()
        
        logger.info(f"[run_id={run_id}] Lock acquired, executing pipeline...")
        
        # 2. Execute pipeline stages with proper commit boundaries
        result = await _execute_pipeline_stages_v2(
            session=session,
            run_id=run_id,
            run_uuid=run_uuid,
            train_model=train_model,
        )
        
        # Determine quality state from result
        # More nuanced logic to avoid false alarms
        raw_inserted = result.get("news_raw_inserted", 0)
        proc_inserted = result.get("news_processed_inserted", 0)
        raw_error = result.get("news_raw_error")
        proc_error = result.get("news_processed_error")
        
        if raw_error or proc_error:
            # Actual errors during ingestion/processing
            quality_state = "degraded"
            result["message"] = f"Pipeline errors: {raw_error or ''} {proc_error or ''}".strip()
        elif raw_inserted == 0 and proc_inserted == 0:
            # No new data at all - could be dedup working or sources haven't updated
            quality_state = "stale"
            result["message"] = "No new articles - sources may not have updated"
        elif raw_inserted > 0 and proc_inserted == 0:
            # Got raw but nothing processed - potential dedup anomaly
            quality_state = "ok"  # This is actually fine - all duplicates
            result["message"] = f"All {raw_inserted} articles were duplicates"
        else:
            quality_state = "ok"
        
        # 3. Record success
        finished_at = datetime.now(timezone.utc)
        duration = (finished_at - started_at).total_seconds()
        
        finalize_run_metrics(
            session, run_id, 
            status="success", 
            quality_state=quality_state,
        )
        session.commit()
        
        logger.info(f"[run_id={run_id}] Pipeline completed in {duration:.1f}s")
        
        return {
            "run_id": run_id,
            "status": "success",
            "quality_state": quality_state,
            "started_at": started_at.isoformat(),
            "finished_at": finished_at.isoformat(),
            "duration_seconds": duration,
            "train_model": train_model,
            **result,
        }
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Pipeline failed: {e}", exc_info=True)
        
        try:
            finalize_run_metrics(
                session, run_id,
                status="failed",
                quality_state="failed",
                error_message=str(e)[:1000],
            )
            session.commit()
        except Exception:
            session.rollback()
        
        return {
            "run_id": run_id,
            "status": "failed",
            "error": str(e),
        }
        
    finally:
        # Always release lock and cleanup
        try:
            release_lock(session, PIPELINE_LOCK_KEY)
            clear_lock_visibility(session, PIPELINE_LOCK_KEY)
            session.commit()
        except Exception:
            session.rollback()
        finally:
            session.close()


async def _execute_pipeline_stages_v2(
    session: Session,
    run_id: str,
    run_uuid: uuid.UUID,
    train_model: bool,
) -> dict:
    """
    Execute pipeline stages with Faz 2 news pipeline integration.
    
    Each stage has proper commit boundaries and metrics updates.
    """
    from app.settings import get_settings
    
    settings = get_settings()
    result = {}
    
    # -------------------------------------------------------------------------
    # Stage 1a: News ingestion β†’ news_raw (FAZ 2)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 1a: News ingestion β†’ news_raw")
    try:
        from pipelines.ingestion.news import ingest_news_to_raw
        
        raw_stats = ingest_news_to_raw(
            session=session,
            run_id=run_uuid,
        )
        session.commit()
        
        result["news_raw_inserted"] = raw_stats.get("inserted", 0)
        result["news_raw_duplicates"] = raw_stats.get("duplicates", 0)
        
        update_run_metrics(
            session, run_id,
            news_raw_inserted=raw_stats.get("inserted", 0),
            news_raw_duplicates=raw_stats.get("duplicates", 0),
        )
        session.commit()
        
        logger.info(f"[run_id={run_id}] news_raw: {raw_stats.get('inserted', 0)} inserted")
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 1a failed: {e}")
        result["news_raw_error"] = str(e)
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 1b: Raw β†’ Processed (FAZ 2)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 1b: news_raw β†’ news_processed")
    try:
        from pipelines.processing.news import process_raw_to_processed
        
        proc_stats = process_raw_to_processed(
            session=session,
            run_id=run_uuid,
            batch_size=200,
        )
        session.commit()
        
        result["news_processed_inserted"] = proc_stats.get("inserted", 0)
        result["news_processed_duplicates"] = proc_stats.get("duplicates", 0)
        
        update_run_metrics(
            session, run_id,
            news_processed_inserted=proc_stats.get("inserted", 0),
            news_processed_duplicates=proc_stats.get("duplicates", 0),
        )
        session.commit()
        
        logger.info(f"[run_id={run_id}] news_processed: {proc_stats.get('inserted', 0)} inserted")
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 1b failed: {e}")
        result["news_processed_error"] = str(e)
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 1c: Cut-off calculation (FAZ 2)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 1c: Computing news cut-off")
    try:
        from pipelines.cutoff import compute_news_cutoff
        
        cutoff_dt = compute_news_cutoff(
            run_datetime=datetime.now(timezone.utc),
            market_tz=settings.market_timezone,
            market_close=settings.market_close_time,
            buffer_minutes=settings.cutoff_buffer_minutes,
        )
        
        result["news_cutoff_time"] = cutoff_dt.isoformat()
        
        update_run_metrics(session, run_id, news_cutoff_time=cutoff_dt)
        session.commit()
        
        logger.info(f"[run_id={run_id}] Cut-off: {cutoff_dt.isoformat()}")
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 1c failed: {e}")
        result["cutoff_error"] = str(e)
    
    # -------------------------------------------------------------------------
    # Stage 1d: Price ingestion (existing)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 1d: Price ingestion")
    try:
        from app.data_manager import ingest_prices
        
        price_stats = ingest_prices(session)
        session.commit()
        
        result["symbols_fetched"] = len(price_stats)
        result["price_bars_updated"] = sum(
            s.get("imported", 0) for s in price_stats.values()
        )
        
        update_run_metrics(
            session, run_id,
            price_bars_updated=result["price_bars_updated"],
        )
        session.commit()
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 1d failed: {e}")
        result["price_error"] = str(e)
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 2: Sentiment scoring (V2 - news_processed based)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 2: Sentiment scoring")
    try:
        from app.ai_engine import score_unscored_processed_articles

        scoring_stats = score_unscored_processed_articles(session)
        session.commit()

        result["articles_scored"] = int(scoring_stats.get("scored_count", 0))
        result["articles_scored_v2"] = int(scoring_stats.get("scored_count", 0))
        result["llm_parse_fail_count"] = int(scoring_stats.get("parse_fail_count", 0))
        result["escalation_count"] = int(scoring_stats.get("escalation_count", 0))
        result["fallback_count"] = int(scoring_stats.get("fallback_count", 0))

        update_run_metrics(
            session,
            run_id,
            articles_scored_v2=result["articles_scored_v2"],
            llm_parse_fail_count=result["llm_parse_fail_count"],
            escalation_count=result["escalation_count"],
            fallback_count=result["fallback_count"],
        )
        session.commit()
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 2 failed: {e}")
        result["scoring_error"] = str(e)
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 3: Sentiment aggregation (existing)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 3: Sentiment aggregation")
    try:
        from app.ai_engine import aggregate_daily_sentiment_v2

        days_aggregated_v2 = aggregate_daily_sentiment_v2(session)
        session.commit()
        
        result["days_aggregated_v2"] = days_aggregated_v2
        
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 3 failed: {e}")
        result["aggregation_error"] = str(e)
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 3.5: FinBERT embedding extraction (TFT-ASRO)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 3.5: FinBERT embedding extraction")
    try:
        from deep_learning.data.embeddings import backfill_embeddings

        emb_stats = backfill_embeddings(days=30, pca_dim=32, batch_size=64)
        session.commit()

        result["tft_embeddings_computed"] = emb_stats.get("embedded", 0)
        result["tft_embeddings_skipped"] = emb_stats.get("skipped", 0)
        result["tft_pca_fitted"] = emb_stats.get("pca_fitted", False)

        update_run_metrics(
            session, run_id,
            tft_embeddings_computed=emb_stats.get("embedded", 0),
        )
        session.commit()

        logger.info(
            f"[run_id={run_id}] FinBERT embeddings: "
            f"{emb_stats.get('embedded', 0)} computed, {emb_stats.get('skipped', 0)} skipped"
        )

    except ImportError:
        logger.info(f"[run_id={run_id}] Stage 3.5 skipped: deep_learning module not available")
    except Exception as e:
        logger.warning(f"[run_id={run_id}] Stage 3.5 failed (non-critical): {e}")
        result["tft_embedding_error"] = str(e)
        session.rollback()

    # -------------------------------------------------------------------------
    # Stage 4: Model training (optional)
    # -------------------------------------------------------------------------
    if train_model:
        logger.info(f"[run_id={run_id}] Stage 4: Model training")
        try:
            from app.ai_engine import train_xgboost_model, save_model_metadata_to_db
            
            train_result = train_xgboost_model(session)
            save_model_metadata_to_db(
                session,
                symbol="HG=F",
                importance=train_result.get("importance", []),
                features=train_result.get("features", []),
                metrics=train_result.get("metrics", {}),
            )
            session.commit()
            
            result["model_trained"] = True
            result["model_metrics"] = train_result.get("metrics", {})
            
            update_run_metrics(
                session, run_id,
                train_mae=train_result.get("metrics", {}).get("mae"),
                val_mae=train_result.get("metrics", {}).get("val_mae"),
            )
            session.commit()
            
        except Exception as e:
            logger.error(f"[run_id={run_id}] Stage 4 failed: {e}")
            result["training_error"] = str(e)
            result["model_trained"] = False
            session.rollback()
    else:
        result["model_trained"] = False

    # -------------------------------------------------------------------------
    # Stage 4.5: TFT-ASRO β€” inference only (training handled by weekly
    # tft-training.yml workflow; daily pipeline never retrains TFT)
    # -------------------------------------------------------------------------
    result["tft_trained"] = False

    # -------------------------------------------------------------------------
    # Stage 5: Generate snapshot
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 5: Generate snapshot")
    snapshot_report = None  # Will be used by Stage 6
    try:
        from app.inference import generate_analysis_report, save_analysis_snapshot
        
        report = generate_analysis_report(session, "HG=F")
        
        if report:
            # Add Faz 2 metadata
            report["quality_state"] = "ok"
            if result.get("news_processed_inserted", 0) == 0:
                report["quality_state"] = "degraded"
                report["message"] = "No fresh news data"
            
            save_analysis_snapshot(session, report, "HG=F")
            session.commit()
            
            result["snapshot_generated"] = True
            snapshot_report = report  # Save for Stage 6
            update_run_metrics(session, run_id, snapshot_generated=True)
            session.commit()
        else:
            result["snapshot_generated"] = False
            
    except Exception as e:
        logger.error(f"[run_id={run_id}] Stage 5 failed: {e}")
        result["snapshot_error"] = str(e)
        result["snapshot_generated"] = False
        session.rollback()
    
    # -------------------------------------------------------------------------
    # Stage 5.5: TFT-ASRO snapshot (parallel to XGBoost snapshot)
    # -------------------------------------------------------------------------
    logger.info(f"[run_id={run_id}] Stage 5.5: TFT-ASRO snapshot")
    try:
        from deep_learning.inference.predictor import generate_tft_analysis
        from deep_learning.config import get_tft_config
        from pathlib import Path

        tft_cfg = get_tft_config()
        ckpt = Path(tft_cfg.training.best_model_path)

        # If checkpoint is not cached locally, try to pull from HF Hub first
        if not ckpt.exists():
            try:
                from deep_learning.models.hub import download_tft_artifacts
                logger.info(f"[run_id={run_id}] TFT checkpoint not found locally – attempting HF Hub download")
                download_tft_artifacts(
                    local_dir=ckpt.parent,
                    repo_id=tft_cfg.training.hf_model_repo,
                )
            except Exception as hub_exc:
                logger.warning(f"[run_id={run_id}] HF Hub download failed: {hub_exc}")

        if ckpt.exists():
            tft_report = generate_tft_analysis(session, "HG=F")

            if "error" not in tft_report:
                result["tft_snapshot_generated"] = True
                update_run_metrics(session, run_id, tft_snapshot_generated=True)
                session.commit()
                logger.info(f"[run_id={run_id}] TFT-ASRO snapshot generated")
            else:
                result["tft_snapshot_generated"] = False
                logger.warning(f"[run_id={run_id}] TFT prediction error: {tft_report.get('error')}")
        else:
            result["tft_snapshot_generated"] = False
            logger.info(f"[run_id={run_id}] Stage 5.5 skipped: no TFT checkpoint found (train-tft workflow has not run yet)")

    except ImportError:
        result["tft_snapshot_generated"] = False
    except Exception as e:
        logger.warning(f"[run_id={run_id}] Stage 5.5 failed (non-critical): {e}")
        result["tft_snapshot_generated"] = False
        session.rollback()

    # -------------------------------------------------------------------------
    # Stage 6: Generate commentary (if any snapshot was generated)
    # -------------------------------------------------------------------------
    has_xgb_snapshot = result.get("snapshot_generated") and snapshot_report
    has_tft_snapshot = result.get("tft_snapshot_generated")

    if has_xgb_snapshot or has_tft_snapshot:
        logger.info(f"[run_id={run_id}] Stage 6: Generate commentary")
        try:
            from app.commentary import generate_and_save_commentary

            report = snapshot_report or {}
            await generate_and_save_commentary(
                session=session,
                symbol="HG=F",
                current_price=report.get("current_price", 0.0),
                predicted_price=report.get("predicted_price", 0.0),
                predicted_return=report.get("predicted_return", 0.0),
                sentiment_index=report.get("sentiment_index", 0.0),
                sentiment_label=report.get("sentiment_label", "Neutral"),
                top_influencers=report.get("top_influencers", []),
                news_count=report.get("data_quality", {}).get("news_count_7d", 0),
            )
            session.commit()

            result["commentary_generated"] = True
            update_run_metrics(session, run_id, commentary_generated=True)
            session.commit()

        except Exception as e:
            logger.warning(f"[run_id={run_id}] Stage 6 failed: {e}")
            result["commentary_generated"] = False
    else:
        logger.warning(f"[run_id={run_id}] Stage 6 skipped: no snapshot generated")
        result["commentary_generated"] = False
    
    return result


# =============================================================================
# arq worker lifecycle
# =============================================================================

async def startup(ctx: dict) -> None:
    """Called when worker starts."""
    logger.info("Worker starting up...")
    init_db()


async def shutdown(ctx: dict) -> None:
    """Called when worker shuts down."""
    logger.info("Worker shutting down...")