File size: 31,522 Bytes
fb7922c
7ca0188
 
 
fb7922c
7ca0188
 
fb7922c
 
 
 
 
7ca0188
 
 
fb7922c
 
830c01e
 
 
 
 
 
fb7922c
 
 
830c01e
 
 
fb7922c
 
830c01e
 
 
fb7922c
 
 
7ca0188
fb7922c
 
7ca0188
 
 
fb7922c
 
 
 
 
 
 
830c01e
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
fb7922c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830c01e
 
 
fb7922c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
fb7922c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0188
fb7922c
 
7ca0188
 
fb7922c
 
 
830c01e
 
 
 
 
 
 
fb7922c
 
 
830c01e
 
 
 
 
 
 
 
 
 
fb7922c
 
 
 
830c01e
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
fb7922c
 
 
830c01e
 
 
fb7922c
 
 
 
 
 
 
 
 
 
830c01e
 
 
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
 
fb7922c
 
 
 
 
 
830c01e
 
fb7922c
 
 
 
7ca0188
fb7922c
 
 
 
 
 
 
 
 
 
830c01e
 
 
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
fb7922c
 
 
830c01e
 
 
fb7922c
 
 
 
 
 
 
 
830c01e
 
 
 
7ca0188
1ab649c
 
 
830c01e
 
 
 
 
 
 
 
 
 
1ab649c
 
830c01e
 
 
 
 
 
 
 
 
 
 
1ab649c
 
 
830c01e
 
 
 
1ab649c
 
7ca0188
830c01e
 
 
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
 
fb7922c
 
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
fb7922c
 
 
830c01e
 
 
 
 
fb7922c
 
 
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
fb7922c
 
 
 
 
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
 
fb7922c
 
 
830c01e
 
 
 
 
fb7922c
 
 
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
830c01e
 
 
fb7922c
 
830c01e
 
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0188
fb7922c
830c01e
 
 
 
fb7922c
 
830c01e
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
f8ac5a2
 
 
fb7922c
f8ac5a2
 
 
 
fb7922c
830c01e
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
 
 
 
 
 
 
 
 
830c01e
 
 
 
fb7922c
 
830c01e
 
 
 
 
 
 
fb7922c
 
830c01e
 
 
 
 
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0188
fb7922c
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0188
418205d
fb7922c
 
 
830c01e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418205d
830c01e
 
 
418205d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb7922c
418205d
 
 
 
 
 
f8ac5a2
 
 
 
 
 
 
 
 
 
 
830c01e
 
 
 
 
 
 
 
 
 
f8ac5a2
 
 
 
 
 
830c01e
 
 
 
 
 
 
 
f8ac5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
830c01e
 
 
 
 
 
f8ac5a2
 
 
 
 
830c01e
 
 
 
 
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
"""Neon-backed, source-labelled CBAO dashboard metrics and Plotly figures."""

from __future__ import annotations

from datetime import datetime, timezone
from typing import Any

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from sklearn.metrics import precision_recall_fscore_support

from src.logging_layer.neon_client import NeonClient


DEFAULT_BEHAVIOUR_SOURCES = ("manual_user", "structured_test", "model_evaluation")
ALL_DATA_SOURCES = (
    "manual_user",
    "structured_test",
    "model_evaluation",
    "synthetic",
    "locust",
    "hypothesis",
)


def _empty_figure(
    title: str, message: str = "No matching evidence is available."
) -> go.Figure:
    figure = go.Figure()
    figure.add_annotation(text=message, x=0.5, y=0.5, showarrow=False)
    figure.update_layout(
        title=title, height=350, xaxis_visible=False, yaxis_visible=False
    )
    return figure


class CBAODashboard:
    """Build examiner-facing metrics without mixing incompatible data sources."""

    def __init__(self, neon: NeonClient | None = None) -> None:
        self.neon = neon or NeonClient()

    @staticmethod
    def _filters(
        data_sources: list[str] | None,
        modality: str | None,
        days: str | int | None,
        configuration_version: str | None,
    ) -> tuple[str, dict[str, Any]]:
        sources = [
            item
            for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES)
            if item in ALL_DATA_SOURCES
        ]
        if not sources:
            sources = list(DEFAULT_BEHAVIOUR_SOURCES)
        params: dict[str, Any] = {
            f"source_{index}": value for index, value in enumerate(sources)
        }
        clauses = [
            "ci.data_source IN ("
            + ",".join(f":source_{i}" for i in range(len(sources)))
            + ")"
        ]
        if modality and modality != "all":
            clauses.append("ci.input_modality = :modality")
            params["modality"] = modality
        if str(days or "all").lower() != "all":
            try:
                day_count = max(1, min(3650, int(days)))
            except (TypeError, ValueError):
                day_count = 30
            clauses.append("ci.timestamp >= NOW() - (:days * INTERVAL '1 day')")
            params["days"] = day_count
        if configuration_version and configuration_version != "all":
            clauses.append("ci.configuration_version = :configuration_version")
            params["configuration_version"] = configuration_version
        return " AND ".join(clauses), params

    def _interaction_frame(
        self,
        data_sources: list[str] | None = None,
        modality: str = "all",
        days: str | int = "30",
        configuration_version: str = "all",
    ) -> pd.DataFrame:
        where, params = self._filters(
            data_sources, modality, days, configuration_version
        )
        rows = self.neon.fetch_all(
            f"""
            SELECT ci.interaction_id, ci.session_id, ci.timestamp, ci.data_source,
              ci.test_run_id, ci.configuration_version, ci.input_modality,
              ci.predicted_intent, ci.intent_confidence, ci.image_category,
              ci.route, ci.matched_record_id, ci.retrieval_score,
              ci.final_confidence, ci.fallback_triggered, ci.response_time_ms,
              ci.time_to_first_response_ms, ci.intent_latency_ms,
              ci.retrieval_latency_ms, ci.vision_latency_ms, ci.speech_latency_ms,
              ci.task_completed, ci.model_used,
              ip.expected_intent, ip.correct AS intent_correct,
              rr.selected_record_id, rr.similarity_score,
              rr.expected_record_id, rr.retrieval_correct,
              fb.fallback_reason,
              ve.ocr_used, ve.ocr_confidence, ve.clip_used, ve.clip_category,
              ve.clip_confidence, ve.qwen_invoked, ve.qwen_success
            FROM chat_interactions ci
            LEFT JOIN intent_predictions ip ON ip.interaction_id = ci.interaction_id
            LEFT JOIN retrieval_results rr ON rr.interaction_id = ci.interaction_id
            LEFT JOIN fallback_events fb ON fb.interaction_id = ci.interaction_id
            LEFT JOIN vision_events ve ON ve.interaction_id = ci.interaction_id
            WHERE {where}
            ORDER BY ci.timestamp DESC
            LIMIT 5000
            """,
            params,
        )
        frame = pd.DataFrame(rows)
        if frame.empty:
            return frame
        frame["timestamp"] = pd.to_datetime(
            frame["timestamp"], utc=True, errors="coerce"
        )
        numeric = (
            "intent_confidence",
            "retrieval_score",
            "final_confidence",
            "response_time_ms",
            "time_to_first_response_ms",
            "intent_latency_ms",
            "retrieval_latency_ms",
            "vision_latency_ms",
            "speech_latency_ms",
            "similarity_score",
            "ocr_confidence",
            "clip_confidence",
        )
        for column in numeric:
            if column in frame:
                frame[column] = pd.to_numeric(frame[column], errors="coerce")
        return frame

    def _feedback_frame(self, where: str, params: dict[str, Any]) -> pd.DataFrame:
        rows = self.neon.fetch_all(
            f"""SELECT fe.rating, fe.frustration_flag, fe.created_at
                  FROM feedback_events fe
                  JOIN chat_interactions ci ON ci.interaction_id = fe.interaction_id
                 WHERE {where}
                 ORDER BY fe.created_at DESC LIMIT 5000""",
            params,
        )
        return pd.DataFrame(rows)

    def metrics(self) -> dict[str, Any]:
        """Compatibility KPI method used by existing callers and tests."""

        if not self.neon.is_configured():
            return {"status": "Neon is not configured"}
        frame = self._interaction_frame()
        if frame.empty:
            return {
                "interactions": 0,
                "sessions": 0,
                "avg_response_ms": None,
                "fallback_rate_pct": None,
                "completion_rate_pct": None,
                "feedback_count": 0,
                "helpful_rate_pct": None,
            }
        where, params = self._filters(None, "all", "30", "all")
        ratings = self._feedback_frame(where, params)
        completed = (
            frame["task_completed"].dropna()
            if "task_completed" in frame
            else pd.Series(dtype=bool)
        )
        helpful = (
            ratings["rating"].eq("helpful")
            if not ratings.empty and "rating" in ratings
            else pd.Series(dtype=bool)
        )
        return {
            "interactions": int(len(frame)),
            "sessions": int(frame["session_id"].nunique()),
            "avg_response_ms": round(float(frame["response_time_ms"].mean()), 1),
            "fallback_rate_pct": round(
                float(frame["fallback_triggered"].fillna(False).mean() * 100), 1
            ),
            "completion_rate_pct": (
                round(float(completed.astype(bool).mean() * 100), 1)
                if len(completed)
                else None
            ),
            "feedback_count": int(len(ratings)),
            "helpful_rate_pct": (
                round(float(helpful.mean() * 100), 1) if len(helpful) else None
            ),
        }

    @staticmethod
    def _kpi_markdown(
        frame: pd.DataFrame, feedback: pd.DataFrame, sources: list[str]
    ) -> str:
        now = datetime.now(timezone.utc).strftime("%d %b %Y %H:%M UTC")
        if frame.empty:
            return (
                "### No matching analytics evidence\n\n"
                f"Filters: `{', '.join(sources)}` 路 Refreshed {now}. "
                "No rates are reported as zero when their denominator is absent."
            )
        fallback = frame["fallback_triggered"].fillna(False).astype(bool)
        completed = frame["task_completed"].dropna()
        response = frame["response_time_ms"].dropna()
        labelled = frame[
            frame["expected_intent"].notna() & frame["intent_correct"].notna()
        ]
        helpful = (
            feedback["rating"].eq("helpful")
            if not feedback.empty
            else pd.Series(dtype=bool)
        )

        def value(number: float | None, suffix: str = "") -> str:
            return "Not measurable" if number is None else f"{number:,.1f}{suffix}"

        completion = (
            float(completed.astype(bool).mean() * 100) if len(completed) else None
        )
        intent_accuracy = (
            float(labelled["intent_correct"].astype(bool).mean() * 100)
            if len(labelled)
            else None
        )
        helpful_rate = float(helpful.mean() * 100) if len(helpful) else None
        median = float(response.median()) if len(response) else None
        p95 = float(response.quantile(0.95)) if len(response) else None
        return (
            "### Executive overview\n\n"
            f"**Interactions:** {len(frame):,} 路 **Sessions:** {frame['session_id'].nunique():,} 路 "
            f"**Fallback:** {fallback.mean() * 100:.1f}% 路 "
            f"**Completion:** {value(completion, '%')} 路 "
            f"**Median latency:** {value(median, ' ms')} 路 **p95 latency:** {value(p95, ' ms')} 路 "
            f"**Intent accuracy:** {value(intent_accuracy, '%')} (`n={len(labelled)}`) 路 "
            f"**Helpful:** {value(helpful_rate, '%')} (`n={len(feedback)}`)\n\n"
            f"Sources: `{', '.join(sources)}` 路 Refreshed {now}."
        )

    def dashboard(
        self,
        data_sources: list[str] | None = None,
        modality: str = "all",
        days: str = "30",
        configuration_version: str = "all",
    ) -> tuple[Any, ...]:
        """Return dashboard summary, figures and audit tables for Gradio."""

        sources = [
            item
            for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES)
            if item in ALL_DATA_SOURCES
        ]
        if not self.neon.is_configured():
            empty = _empty_figure(
                "Dashboard unavailable",
                "Configure the DATABASE_URL Hugging Face secret.",
            )
            return (
                "### Dashboard unavailable\n\nNeon PostgreSQL is not configured.",
                *([empty] * 15),
                [],
                [],
                [],
                [],
            )
        frame = self._interaction_frame(sources, modality, days, configuration_version)
        where, params = self._filters(sources, modality, days, configuration_version)
        feedback = self._feedback_frame(where, params)
        summary = self._kpi_markdown(
            frame, feedback, sources or list(DEFAULT_BEHAVIOUR_SOURCES)
        )
        if frame.empty:
            empty = _empty_figure("No matching evidence")
            return (summary, *([empty] * 15), [], [], [], [])

        daily = frame.dropna(subset=["timestamp"]).copy()
        daily["date"] = daily["timestamp"].dt.date
        trend = daily.groupby("date", as_index=False).agg(
            interactions=("interaction_id", "count"),
            fallback_rate=(
                "fallback_triggered",
                lambda s: s.fillna(False).mean() * 100,
            ),
        )
        if trend.empty:
            overview = _empty_figure("Interaction trend")
        elif len(trend) == 1:
            hourly = (
                daily.assign(hour=daily["timestamp"].dt.floor("h"))
                .groupby("hour", as_index=False)
                .agg(
                    interactions=("interaction_id", "count"),
                    fallback_rate=(
                        "fallback_triggered",
                        lambda s: s.fillna(False).mean() * 100,
                    ),
                )
            )
            overview = px.bar(
                hourly,
                x="hour",
                y="interactions",
                color="fallback_rate",
                text_auto=True,
                title="Same-day interaction volume by hour",
                labels={
                    "hour": "Hour",
                    "interactions": "Interactions",
                    "fallback_rate": "Fallback %",
                },
            )
        else:
            overview = px.line(
                trend,
                x="date",
                y=["interactions", "fallback_rate"],
                markers=True,
                title="Daily interaction volume and fallback trend",
            )

        intents = (
            frame["predicted_intent"]
            .fillna("unknown")
            .value_counts()
            .rename_axis("intent")
            .reset_index(name="count")
        )
        intent_chart = px.bar(
            intents, x="count", y="intent", orientation="h", title="Intent distribution"
        )
        confidence_chart = px.histogram(
            frame,
            x="intent_confidence",
            color="predicted_intent",
            nbins=20,
            title="Intent confidence distribution",
        )
        confidence_chart.add_vline(
            x=0.55, line_dash="dash", annotation_text="runtime threshold"
        )

        fallback_by = (
            frame.assign(
                fallback=frame["fallback_triggered"].fillna(False).astype(bool)
            )
            .groupby(
                ["predicted_intent", "input_modality"], dropna=False, as_index=False
            )
            .agg(
                interactions=("interaction_id", "count"),
                fallback_rate=("fallback", "mean"),
            )
        )
        fallback_by["fallback_rate"] *= 100
        fallback_chart = px.bar(
            fallback_by,
            x="predicted_intent",
            y="fallback_rate",
            color="input_modality",
            barmode="group",
            title="Fallback rate by intent and modality",
        )

        modality_summary = frame.groupby(
            "input_modality", dropna=False, as_index=False
        ).agg(
            interactions=("interaction_id", "count"),
            completion_rate=(
                "task_completed",
                lambda s: (
                    s.dropna().astype(bool).mean() * 100
                    if len(s.dropna())
                    else float("nan")
                ),
            ),
            median_latency_ms=("response_time_ms", "median"),
        )
        modality_chart = px.bar(
            modality_summary,
            x="input_modality",
            y="interactions",
            color="completion_rate",
            title="Modality usage and completion",
        )

        retrieval = frame[frame["matched_record_id"].fillna("").ne("")].copy()
        retrieval_chart = (
            px.histogram(
                retrieval,
                x="retrieval_score",
                color="input_modality",
                nbins=20,
                title="RAG similarity distribution",
            )
            if not retrieval.empty
            else _empty_figure("RAG similarity distribution")
        )

        sessions = frame.groupby("session_id", as_index=False).agg(
            turns=("interaction_id", "count"),
            fallbacks=("fallback_triggered", lambda s: s.fillna(False).sum()),
            completed=(
                "task_completed",
                lambda s: s.dropna().astype(bool).any() if len(s.dropna()) else False,
            ),
        )
        session_chart = (
            px.histogram(sessions, x="turns", title="Session length distribution")
            if not sessions.empty
            else _empty_figure("Session length")
        )

        ordered = frame.dropna(
            subset=["timestamp", "session_id", "predicted_intent"]
        ).sort_values(["session_id", "timestamp"])
        pairs: list[tuple[str, str]] = []
        for _session, group in ordered.groupby("session_id"):
            values = list(dict.fromkeys(group["predicted_intent"].astype(str).tolist()))
            pairs.extend(
                (left, right)
                for index, left in enumerate(values)
                for right in values[index + 1 :]
            )
        if pairs:
            pair_frame = pd.DataFrame(pairs, columns=["intent_a", "intent_b"])
            matrix = pd.crosstab(pair_frame["intent_a"], pair_frame["intent_b"])
            cooccurrence_chart = px.imshow(
                matrix, text_auto=True, title="Session intent co-occurrence"
            )
            session_count = max(1, ordered["session_id"].nunique())
            intent_sessions = (
                ordered.groupby("predicted_intent")["session_id"].nunique().to_dict()
            )
            pair_counts = (
                pair_frame.groupby(["intent_a", "intent_b"])
                .size()
                .reset_index(name="sessions_together")
            )
            rules: list[dict[str, Any]] = []
            for row in pair_counts.itertuples(index=False):
                support = row.sessions_together / session_count
                p_a = intent_sessions.get(row.intent_a, 0) / session_count
                p_b = intent_sessions.get(row.intent_b, 0) / session_count
                confidence = row.sessions_together / max(
                    1, intent_sessions.get(row.intent_a, 0)
                )
                lift = support / (p_a * p_b) if p_a and p_b else 0.0
                rules.append(
                    {
                        "intent_a": row.intent_a,
                        "intent_b": row.intent_b,
                        "support": round(support, 4),
                        "confidence": round(confidence, 4),
                        "lift": round(lift, 4),
                        "sessions": int(row.sessions_together),
                    }
                )
            association_table = sorted(
                rules, key=lambda item: (item["lift"], item["support"]), reverse=True
            )
        else:
            cooccurrence_chart = _empty_figure(
                "Session intent co-occurrence",
                "At least two intents in one session are required.",
            )
            association_table = []

        latency_columns = [
            "intent_latency_ms",
            "retrieval_latency_ms",
            "vision_latency_ms",
            "speech_latency_ms",
        ]
        latency = (
            frame[latency_columns]
            .median()
            .rename_axis("component")
            .reset_index(name="median_ms")
        )
        latency_chart = px.bar(
            latency, x="component", y="median_ms", title="Median component latency"
        )
        latency_distribution = px.histogram(
            frame,
            x="response_time_ms",
            color="input_modality",
            nbins=30,
            title="End-to-end response-time distribution",
        )

        vision = frame[
            (frame["clip_used"] == True)
            | (frame["ocr_used"] == True)
            | (frame["qwen_invoked"] == True)
        ].copy()  # noqa: E712
        if vision.empty:
            vision_chart = _empty_figure("Vision route evidence")
        else:
            vision_melt = pd.DataFrame(
                {
                    "route": ["CLIP", "OCR", "Qwen"],
                    "events": [
                        vision["clip_used"].fillna(False).sum(),
                        vision["ocr_used"].fillna(False).sum(),
                        vision["qwen_invoked"].fillna(False).sum(),
                    ],
                }
            )
            vision_chart = px.bar(
                vision_melt, x="route", y="events", title="Vision route evidence"
            )

        labelled = frame[
            frame["expected_intent"].notna() & frame["intent_correct"].notna()
        ].copy()
        intent_table = []
        if not labelled.empty:
            labels = sorted(
                set(labelled["expected_intent"].astype(str))
                | set(labelled["predicted_intent"].astype(str))
            )
            precision, recall, f1, support = precision_recall_fscore_support(
                labelled["expected_intent"].astype(str),
                labelled["predicted_intent"].astype(str),
                labels=labels,
                zero_division=0,
            )
            confidences = (
                labelled.groupby("predicted_intent")["intent_confidence"]
                .mean()
                .to_dict()
            )
            intent_table = [
                {
                    "intent": label,
                    "precision": round(float(precision[i]), 4),
                    "recall": round(float(recall[i]), 4),
                    "f1": round(float(f1[i]), 4),
                    "support": int(support[i]),
                    "avg_confidence": round(float(confidences.get(label, 0)), 4),
                }
                for i, label in enumerate(labels)
            ]
            confusion = pd.crosstab(
                labelled["expected_intent"], labelled["predicted_intent"]
            )
            confusion_chart = px.imshow(
                confusion,
                text_auto=True,
                title=f"Intent confusion matrix (n={len(labelled)})",
            )
        else:
            confusion_chart = _empty_figure(
                "Intent confusion matrix",
                "No interactions with expected intent labels.",
            )

        if feedback.empty or "rating" not in feedback:
            feedback_chart = _empty_figure(
                "Satisfaction and inferred friction", "No feedback has been collected."
            )
        else:
            feedback_counts = (
                feedback.assign(
                    friction=feedback.get("frustration_flag", False)
                    .fillna(False)
                    .map({True: "inferred friction", False: "no friction flag"})
                )
                .groupby(["rating", "friction"], as_index=False)
                .size()
            )
            feedback_chart = px.bar(
                feedback_counts,
                x="rating",
                y="size",
                color="friction",
                barmode="group",
                title="Feedback and inferred friction indicators",
            )

        # Load evidence is queried independently so selecting Locust is not
        # required and never changes passenger-behaviour KPIs.
        locust = self._interaction_frame(["locust"], "all", days, configuration_version)
        if locust.empty:
            load_chart = _empty_figure(
                "Load-test performance",
                "No Locust run is stored for this time/configuration filter.",
            )
        else:
            load_summary = locust.groupby(
                "test_run_id", dropna=False, as_index=False
            ).agg(
                requests=("interaction_id", "count"),
                median_ms=("response_time_ms", "median"),
                p95_ms=("response_time_ms", lambda s: s.quantile(0.95)),
                failure_rate=(
                    "fallback_triggered",
                    lambda s: s.fillna(False).mean() * 100,
                ),
            )
            load_chart = px.bar(
                load_summary,
                x="test_run_id",
                y="p95_ms",
                color="failure_rate",
                hover_data=["requests", "median_ms"],
                title="Load-test p95 latency and failure proxy",
            )

        optimization_rows = self.neon.fetch_all(
            """SELECT experiment_name, configuration_version, model_name, precision_name,
                      metric_name, metric_value, sample_size, created_at
                 FROM optimization_results ORDER BY created_at DESC LIMIT 1000"""
        )
        optimization = pd.DataFrame(optimization_rows)
        if optimization.empty:
            optimization_chart = _empty_figure(
                "Optimization comparison",
                "No executed optimization results are stored.",
            )
        else:
            optimization_chart = px.bar(
                optimization,
                x="configuration_version",
                y="metric_value",
                color="metric_name",
                facet_row="experiment_name",
                barmode="group",
                title="Baseline versus optimized configurations",
                hover_data=["model_name", "precision_name", "sample_size"],
            )
        fallback_table = (
            fallback_by.sort_values(["fallback_rate", "interactions"], ascending=False)
            .round(3)
            .to_dict("records")
        )
        data_quality = [
            {
                "measure": "Dashboard interactions",
                "sample_size": len(frame),
                "rule": "Filtered by explicit data_source",
            },
            {
                "measure": "Labelled intent cases",
                "sample_size": len(labelled),
                "rule": "Accuracy excludes unlabelled interactions",
            },
            {
                "measure": "Feedback responses",
                "sample_size": len(feedback),
                "rule": "No feedback is reported as not measurable",
            },
            {
                "measure": "Retrieved interactions",
                "sample_size": len(retrieval),
                "rule": "RAG charts require a selected record",
            },
            {
                "measure": "Labelled retrieval cases",
                "sample_size": int(frame["retrieval_correct"].notna().sum()),
                "rule": "Retrieval accuracy excludes unlabelled interactions",
            },
            {
                "measure": "Locust requests (independent dataset)",
                "sample_size": len(locust),
                "rule": "Load evidence is isolated from passenger behaviour metrics",
            },
        ]
        return (
            summary,
            overview,
            intent_chart,
            confidence_chart,
            confusion_chart,
            fallback_chart,
            modality_chart,
            retrieval_chart,
            vision_chart,
            session_chart,
            cooccurrence_chart,
            latency_chart,
            latency_distribution,
            feedback_chart,
            load_chart,
            optimization_chart,
            intent_table,
            fallback_table,
            association_table,
            data_quality,
        )

    def render(self) -> tuple[str, list[list[str]]]:
        metrics = self.metrics()
        if "status" in metrics:
            return (
                f"**Dashboard unavailable:** {metrics['status']}.",
                [["status", str(metrics["status"])]],
            )
        rows = [
            [
                key.replace("_", " ").title(),
                "Not measurable" if value is None else str(value),
            ]
            for key, value in metrics.items()
        ]
        return (
            "### Executive KPI snapshot\n\n"
            + " 路 ".join(f"**{row[0]}:** {row[1]}" for row in rows),
            rows,
        )

    def interaction_review(
        self, interaction_id: str | None
    ) -> tuple[str, dict[str, Any]]:
        interaction_id = (interaction_id or "").strip()
        if not interaction_id:
            return "Enter an interaction ID.", {}
        if not self.neon.is_configured():
            return "Review unavailable: Neon is not configured.", {}
        rows = self.neon.fetch_all(
            """
            SELECT interaction_id, timestamp, data_source, configuration_version,
              input_modality, sanitized_query, transcribed_text_sanitized,
              image_category, predicted_intent, intent_confidence,
              extracted_entities_json, route, matched_record_id,
              matched_record_name, retrieval_score, final_confidence,
              fallback_triggered, response_time_ms, time_to_first_response_ms,
              intent_latency_ms, retrieval_latency_ms, vision_latency_ms,
              speech_latency_ms, task_completed, model_used,
              sources_used_json, safety_notes_json
            FROM chat_interactions WHERE interaction_id = :interaction_id LIMIT 1
            """,
            {"interaction_id": interaction_id},
        )
        if not rows:
            return "No matching interaction was found.", {}
        return "Interaction evidence loaded.", rows[0]

    def search_interactions(
        self,
        search_text: str | None = None,
        data_sources: list[str] | None = None,
        modality: str = "all",
        limit: int | float = 25,
    ) -> tuple[str, list[dict[str, Any]], Any]:
        """Search sanitized evidence without requiring a known interaction ID."""

        if not self.neon.is_configured():
            return (
                "Search unavailable: Neon is not configured.",
                [],
                {"choices": [], "value": None},
            )
        sources = [
            item
            for item in (data_sources or DEFAULT_BEHAVIOUR_SOURCES)
            if item in ALL_DATA_SOURCES
        ]
        if not sources:
            sources = list(DEFAULT_BEHAVIOUR_SOURCES)
        try:
            row_limit = max(1, min(100, int(limit)))
        except (TypeError, ValueError):
            row_limit = 25
        params: dict[str, Any] = {
            f"source_{index}": value for index, value in enumerate(sources)
        }
        clauses = [
            "ci.data_source IN ("
            + ",".join(f":source_{index}" for index in range(len(sources)))
            + ")"
        ]
        if modality and modality != "all":
            clauses.append("ci.input_modality = :modality")
            params["modality"] = modality
        term = (search_text or "").strip()
        if term:
            params["term"] = f"%{term}%"
            clauses.append(
                "(ci.interaction_id ILIKE :term OR ci.sanitized_query ILIKE :term "
                "OR ci.predicted_intent ILIKE :term OR ci.matched_record_id ILIKE :term "
                "OR ci.matched_record_name ILIKE :term OR ci.image_category ILIKE :term)"
            )
        params["limit"] = row_limit
        rows = self.neon.fetch_all(
            f"""
            SELECT ci.timestamp, ci.interaction_id, ci.data_source,
              ci.input_modality, ci.sanitized_query, ci.predicted_intent,
              ci.intent_confidence, ci.matched_record_id, ci.matched_record_name,
              ci.final_confidence, ci.fallback_triggered
            FROM chat_interactions ci
            WHERE {' AND '.join(clauses)}
            ORDER BY ci.timestamp DESC
            LIMIT :limit
            """,
            params,
        )
        choices = [
            (
                f"{row.get('interaction_id')} | {str(row.get('sanitized_query') or '')[:70]}",
                row.get("interaction_id"),
            )
            for row in rows
            if row.get("interaction_id")
        ]
        dropdown = {"choices": choices, "value": choices[0][1] if choices else None}
        if not rows:
            return "No matching sanitized interactions were found.", [], dropdown
        scope = "recent interactions" if not term else f"matches for `{term}`"
        return (
            f"Found **{len(rows)}** {scope}. Choose one below to load its full evidence.",
            rows,
            dropdown,
        )