File size: 29,068 Bytes
5246c92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Observability & monitoring for OpenCodeReview.

Provides a single-entry-point module for all tracing, cost tracking,
metadata attribution, health checks, and alerting concerns.

Backends
--------
* **LangSmith** β€” automatic via ``LANGSMITH_API_KEY`` / ``LANGSMITH_PROJECT``
  (also accepts legacy ``LANGCHAIN_API_KEY`` for back-compat) env vars.
  LangGraph/LangChain reads these at import time and starts tracing
  without any per-call code.
* **Langfuse** β€” explicit ``CallbackHandler`` instantiated only when
  ``LANGFUSE_PUBLIC_KEY`` and ``LANGFUSE_SECRET_KEY`` are set.

Usage
-----
    from backend.observability import get_langfuse_handler, build_run_metadata

    handler = get_langfuse_handler()
    metadata = build_run_metadata(source="cli", repo="org/repo", pr_number=42)
    config = {"configurable": {"thread_id": "..."}, "metadata": metadata}
    if handler:
        config["callbacks"] = [handler]
"""

from __future__ import annotations

import logging
import os
import platform
import time
import uuid
from contextlib import contextmanager
from datetime import datetime, timezone
from typing import Any, Generator, Optional

logger = logging.getLogger(__name__)

# ─── LangSmith (automatic, env-var-driven) ──────────────────────────────────


def is_langsmith_enabled() -> bool:
    """Return True if LangSmith tracing is configured via env vars.

    Checks both the new ``LANGSMITH_API_KEY`` (preferred) and legacy
    ``LANGCHAIN_API_KEY`` env vars for backward compatibility.
    """
    return bool(
        os.environ.get("LANGSMITH_API_KEY", "").strip()
        or os.environ.get("LANGCHAIN_API_KEY", "").strip()
    )


def enable_langsmith(api_key: str, project: str = "") -> None:
    """Set the environment variables that LangSmith reads at runtime.

    Per the official LangSmith docs (https://docs.langchain.com/langsmith/trace-with-langgraph):
    the modern env vars are ``LANGSMITH_TRACING`` and ``LANGSMITH_API_KEY``.
    We also set the legacy ``LANGCHAIN_*`` vars for backward compatibility
    with older LangChain versions.

    Call this at startup **before** any LangChain/LangGraph imports so that
    the tracing is active from the first call.
    """
    # Modern env vars (required by langsmith-sdk >= 0.7)
    os.environ["LANGSMITH_TRACING"] = "true"
    os.environ["LANGSMITH_ENDPOINT"] = os.environ.get(
        "LANGSMITH_ENDPOINT", "https://api.smith.langchain.com"
    )
    os.environ["LANGSMITH_API_KEY"] = api_key
    # Legacy env vars (backward compat with older LangChain)
    os.environ["LANGCHAIN_TRACING_V2"] = "true"
    os.environ["LANGCHAIN_API_KEY"] = api_key
    if project:
        os.environ["LANGSMITH_PROJECT"] = project
        os.environ["LANGCHAIN_PROJECT"] = project
    logger.info(
        "LangSmith tracing enabled (project=%s)",
        project or os.environ.get("LANGSMITH_PROJECT", "default"),
    )


def disable_langsmith() -> None:
    """Remove LangSmith env vars so tracing stops."""
    # Modern vars
    os.environ.pop("LANGSMITH_TRACING", None)
    os.environ.pop("LANGSMITH_ENDPOINT", None)
    os.environ.pop("LANGSMITH_API_KEY", None)
    # Legacy vars
    os.environ.pop("LANGCHAIN_TRACING_V2", None)
    os.environ.pop("LANGCHAIN_API_KEY", None)
    # Keep project name in case user wants to set it separately


# ─── Langfuse (explicit callback) ──────────────────────────────────────────


def is_langfuse_enabled() -> bool:
    """Return True if Langfuse keys are present in the environment."""
    pk = os.environ.get("LANGFUSE_PUBLIC_KEY", "").strip()
    sk = os.environ.get("LANGFUSE_SECRET_KEY", "").strip()
    return bool(pk and sk)


def get_langfuse_handler():
    """Return a bare Langfuse ``CallbackHandler`` if keys are configured, else None.

    In langfuse v4+ the ``CallbackHandler`` constructor only accepts
    ``public_key`` and ``trace_context`` β€” trace-level metadata (name, tags,
    user_id, session_id, metadata) is set via the ``propagate_attributes()``
    context manager instead.  Use :func:`langfuse_trace` to wrap your graph
    execution with proper trace attributes.
    """
    if not is_langfuse_enabled():
        return None

    try:
        from langfuse.langchain import CallbackHandler

        # CallbackHandler reads env vars automatically in v4+.
        # No trace metadata params are passed β€” those go through
        # propagate_attributes() instead.
        return CallbackHandler()
    except ImportError:
        logger.warning(
            "langfuse not available β€” skipping tracing",
            exc_info=True,
        )
        return None
    except Exception as exc:
        logger.warning(
            "Failed to initialise Langfuse handler: %s",
            exc,
            exc_info=True,
        )
        return None


@contextmanager
def langfuse_trace(
    trace_name: str = "opencodereview",
    tags: Optional[list[str]] = None,
    user_id: Optional[str] = None,
    session_id: Optional[str] = None,
    metadata: Optional[dict[str, Any]] = None,
) -> Generator[Any, None, None]:
    """Context manager that wraps a LangGraph execution block in Langfuse trace attributes.

    In langfuse v4+, trace-level metadata (name, tags, user_id, session_id,
    metadata) must be set via the ``propagate_attributes()`` context manager
    rather than passed to ``CallbackHandler()``.  This helper creates the
    handler and the ``propagate_attributes`` wrapper in one step.

    Usage
    -----
        with langfuse_trace(
            trace_name="opencodereview/review/psf/requests#42",
            tags=["gradio_ui", "psf/requests"],
            session_id=thread_id,
            metadata={"repo": "psf/requests", "pr_number": 42},
        ) as handler:
            if handler:
                config["callbacks"].append(handler)
            graph.stream(initial_state, config)
    """
    handler = None
    if not is_langfuse_enabled():
        yield None
        return

    try:
        from langfuse.langchain import CallbackHandler

        handler = CallbackHandler()
    except Exception:
        yield None
        return

    # Build propagate_attributes kwargs
    attrs: dict[str, Any] = {}
    if trace_name:
        attrs["trace_name"] = trace_name
    if tags:
        attrs["tags"] = tags
    if user_id:
        attrs["user_id"] = user_id
    if session_id:
        attrs["session_id"] = session_id
    if metadata:
        attrs["metadata"] = metadata

    if attrs:
        try:
            from langfuse import propagate_attributes as _propagate_attributes
        except Exception as exc:
            logger.debug(
                "propagate_attributes not available β€” yielding bare handler: %s",
                exc,
            )
            yield handler
            return

        # yield is OUTSIDE try/except so user-code exceptions propagate
        with _propagate_attributes(**attrs):
            yield handler
    else:
        yield handler


# ─── Run metadata ──────────────────────────────────────────────────────────


def build_run_metadata(
    source: str = "cli",
    repo: str = "",
    pr_number: int = 0,
    session_id: Optional[str] = None,
    user_id: Optional[str] = None,
    prompt_versions: Optional[dict[str, str]] = None,
    extra: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
    """Build a metadata dict attached to every trace/span.

    Parameters
    ----------
    source : str
        ``"cli"`` or ``"gradio_ui"``.
    repo : str
        GitHub repository being reviewed (e.g. ``"psf/requests"``).
    pr_number : int
        PR number being reviewed.
    session_id : str or None
        Unique session / thread identifier.
    user_id : str or None
        GitHub username (CLI) or anonymised token (Gradio).
    prompt_versions : dict or None
        Map of reviewer name β†’ prompt file version (e.g.
        ``{"correctness": "v1", "security": "v1"}``).
    extra : dict or None
        Any additional key-value pairs to attach.

    Returns
    -------
    dict
        Flat metadata dict suitable for ``config["metadata"]``.
    """
    meta: dict[str, Any] = {
        "source": source,
        "app": "opencodereview",
        "host": platform.node(),
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }

    if repo:
        meta["repo"] = repo
    if pr_number:
        meta["pr_number"] = pr_number
    if session_id:
        meta["session_id"] = session_id
    if user_id:
        meta["user_id"] = user_id
    if prompt_versions:
        meta["prompt_versions"] = prompt_versions
    if extra:
        meta.update(extra)

    return meta


# ─── Cost tracking ─────────────────────────────────────────────────────────


# Per-1M-token pricing (USD), keyed by model name.
# Groq source:  https://console.groq.com/docs/pricing   (as of 2025-07)
# NOTE: Gemini rates below are APPROXIMATE published per-1M-token rates
#       (USD) and may drift over time β€” verify against Google's pricing page
#       before relying on them for billing reconciliation.
MODEL_PRICING: dict[str, dict[str, float]] = {
    # ── Groq ──────────────────────────────────────────────────────────
    "llama-3.3-70b-versatile": {"input": 0.59, "output": 0.79},
    # ── Google Gemini ─────────────────────────────────────────────────
    # Approximate published per-1M-token rates (USD) for Gemini Flash-Lite.
    "gemini-3.1-flash-lite": {"input": 0.10, "output": 0.40},
    # Fallback for unknown models β€” pessimistic estimate
    "__default__": {"input": 1.00, "output": 1.00},
}

# Backward-compatible alias β€” previously Groq-only; now the shared table
# so any external references keep resolving.
GROQ_PRICING = MODEL_PRICING


def estimate_model_cost(
    model: str,
    input_tokens: int,
    output_tokens: int,
) -> float | None:
    """Estimate the USD cost of an LLM call by looking up ``MODEL_PRICING``.

    Parameters
    ----------
    model : str
        Model name. Unknown models return None; free-suffix models have a
        zero catalog estimate, never a claimed billing charge.
    input_tokens : int
        Number of tokens in the prompt (system + user messages).
    output_tokens : int
        Number of tokens in the completion.

    Returns
    -------
    float
        Estimated cost in USD, or None when no known price is available.
    """
    if model.endswith(":free"):
        return 0.0
    pricing = MODEL_PRICING.get(model)
    if pricing is None:
        return None
    input_cost = (input_tokens / 1_000_000) * pricing["input"]
    output_cost = (output_tokens / 1_000_000) * pricing["output"]
    return round(input_cost + output_cost, 6)


def estimate_groq_cost(
    model: str,
    input_tokens: int,
    output_tokens: int,
) -> float | None:
    """Estimate the USD cost of a Groq LLM call (backward-compatible).

    Thin wrapper around :func:`estimate_model_cost`.  Kept so existing
    callers (``app.py``, ``main.py``, :class:`TokenCostCallback`) keep
    working unchanged β€” it now also prices Gemini and any other model in
    :data:`MODEL_PRICING` correctly instead of using the Groq-only table.
    """
    return estimate_model_cost(model, input_tokens, output_tokens)


def format_cost(cost_usd: float) -> str:
    """Format a USD cost for human-readable display."""
    if cost_usd < 0.001:
        return f"${cost_usd * 1000:.2f}β€―mΒ’"
    return f"${cost_usd:.4f}"


# ─── Health check helpers ──────────────────────────────────────────────────


class HealthStatus:
    """Aggregate health of the observability and API connectivity."""

    def __init__(self) -> None:
        self.langsmith: bool = is_langsmith_enabled()
        self.langfuse: bool = is_langfuse_enabled()
        self.groq: bool = bool(os.environ.get("GROQ_API_KEY", "").strip())
        self.github: bool = bool(os.environ.get("GITHUB_TOKEN", "").strip())

    @property
    def any_tracing(self) -> bool:
        return self.langsmith or self.langfuse

    def summary(self) -> dict[str, str]:
        """Return a dict of component β†’ status string."""
        return {
            "LangSmith": "βœ… Active" if self.langsmith else "β›” Not configured",
            "Langfuse": "βœ… Active" if self.langfuse else "β›” Not configured",
            "Groq API": "βœ… Key set" if self.groq else "β›” No key",
            "GitHub API": "βœ… Token set" if self.github else "β›” No token",
        }


def check_groq_connectivity() -> tuple[bool, str]:
    """Lightweight Groq connectivity check β€” does not consume quota.

    Uses ``urllib.request`` from stdlib (no extra dependencies).

    Returns ``(ok, message)``.
    """
    import json as _json
    import urllib.error as _urlerror
    import urllib.request as _urlreq

    api_key = os.environ.get("GROQ_API_KEY", "").strip()
    if not api_key:
        return False, "No GROQ_API_KEY set"

    try:
        req = _urlreq.Request(
            "https://api.groq.com/openai/v1/models",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
            method="GET",
        )
        with _urlreq.urlopen(req, timeout=10) as resp:
            if resp.status == 200:
                data = _json.loads(resp.read().decode("utf-8"))
                models = data.get("data", [])
                count = len(models)
                return True, f"Reachable β€” {count} models available"
            else:
                return False, f"HTTP {resp.status}"
    except _urlerror.HTTPError as exc:
        if exc.code == 401:
            return False, "Invalid API key (401)"
        return False, f"HTTP {exc.code}"
    except Exception as exc:
        return False, str(exc)


def check_langfuse_connectivity() -> tuple[bool, str]:
    """Lightweight Langfuse connectivity check.

    Returns ``(ok, message)``.
    """
    if not is_langfuse_enabled():
        return False, "Not configured"

    try:
        from langfuse import Langfuse

        lf = Langfuse()
        lf.auth_check()
        return True, "Connected"
    except Exception as exc:
        return False, str(exc)


# ─── Token cost callback (accumulates LLM usage across a run) ────────────


class TokenCostCallback:
    """Accumulates per-model token usage & TTFT from LangChain LLM calls.

    Also tracks **TTFT** (Time to First Token) by recording a timestamp
    at ``on_chat_model_start`` and computing elapsed time at ``on_llm_end``.
    For non-streaming LLM calls this is effectively the full request duration;
    for streaming it would be the time to the first chunk.

    Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` can
    be imported even when ``langchain-core`` has version incompatibilities
    (e.g. on Hugging Face Spaces).  Only ``on_llm_end`` is overridden;
    all other lifecycle events are ignored.

    Usage
    -----
        counter = TokenCostCallback()
        config["callbacks"] = [counter, langfuse_handler]  # if langfuse
        ... run graph ...
        print(counter.summary())
    """

    raise_error: bool = False
    ignore_llm: bool = False
    ignore_chain: bool = False
    ignore_agent: bool = False
    ignore_retriever: bool = False
    ignore_chat_model: bool = False
    ignore_custom_event: bool = False
    ignore_retry: bool = False
    run_inline: bool = False

    def __init__(self) -> None:
        self.usage: list[dict[str, Any]] = []
        self._start_times: dict[str, float] = {}  # run_id -> timestamp

    @property
    def total_input_tokens(self) -> int:
        return sum(u.get("input_tokens", 0) for u in self.usage)

    @property
    def total_output_tokens(self) -> int:
        return sum(u.get("output_tokens", 0) for u in self.usage)

    @property
    def total_cost(self) -> float:
        return sum(u.get("cost") or 0.0 for u in self.usage)

    @property
    def total_ttft(self) -> float:
        """Total TTFT across all LLM calls, in seconds."""
        ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
        return sum(ttfts)

    @property
    def avg_ttft(self) -> Optional[float]:
        """Average TTFT across all LLM calls, in seconds (None if no calls)."""
        ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]
        if not ttfts:
            return None
        return sum(ttfts) / len(ttfts)

    def on_chain_start(self, *args, **kwargs) -> None:
        pass

    def on_chain_end(self, *args, **kwargs) -> None:
        pass

    def on_chat_model_start(self, *args, **kwargs) -> None:
        """Record start timestamp for TTFT measurement.

        ``**kwargs`` contains ``run_id`` which we use as the key.
        """
        run_id = kwargs.get("run_id")
        if run_id:
            self._start_times[str(run_id)] = time.time()

    def on_llm_start(self, *args, **kwargs) -> None:
        """Fallback: record start timestamp if ``on_chat_model_start`` wasn't called."""
        run_id = kwargs.get("run_id")
        if run_id and str(run_id) not in self._start_times:
            self._start_times[str(run_id)] = time.time()

    def on_llm_error(self, error, **kwargs) -> None:
        self._cleanup_run(kwargs.get("run_id"))

    def on_chain_error(self, error, **kwargs) -> None:
        pass

    def on_tool_error(self, error, **kwargs) -> None:
        pass

    def on_retriever_error(self, error, **kwargs) -> None:
        pass

    def on_llm_end(self, response, **kwargs) -> None:
        """LangChain callback β€” called after each LLM invocation.

        Computes TTFT from the recorded start time and captures token usage.
        ``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and other
        metadata that LangChain passes to callback handlers.
        """
        try:
            run_key = str(kwargs.get("run_id", ""))

            # Compute TTFT (time from start to first token / completion)
            ttft: Optional[float] = None
            if run_key in self._start_times:
                ttft = round(time.time() - self._start_times.pop(run_key), 3)

            usage = response.llm_output or {}
            token_usage = usage.get("token_usage", {}) or {}
            model = usage.get("model_name", "") or ""

            input_tokens = token_usage.get("prompt_tokens", 0) or 0
            output_tokens = token_usage.get("completion_tokens", 0) or 0

            if input_tokens > 0 or output_tokens > 0:
                reported = token_usage.get("cost", usage.get("cost"))
                if isinstance(reported, (int, float)) and not isinstance(reported, bool) and reported >= 0:
                    cost, cost_source = float(reported), "provider_reported"
                else:
                    cost = estimate_model_cost(model, input_tokens, output_tokens)
                    cost_source = "free_model_estimate" if model.endswith(":free") else "estimated" if cost is not None else "unknown"
                entry: dict[str, Any] = {
                    "model": model,
                    "input_tokens": input_tokens,
                    "output_tokens": output_tokens,
                    "cost": cost,
                    "cost_source": cost_source,
                }
                if ttft is not None:
                    entry["ttft_seconds"] = ttft
                self.usage.append(entry)
            else:
                self._cleanup_run(run_key)
        except Exception:
            self._cleanup_run(run_key)
            pass  # Best-effort β€” don't let cost tracking crash the run

    def _cleanup_run(self, run_id: Any) -> None:
        """Remove a run_id from the start times map (cleanup on error)."""
        if run_id:
            self._start_times.pop(str(run_id), None)

    def details(self) -> dict:
        sources = {item.get("cost_source", "estimated") for item in self.usage}
        complete = bool(self.usage) and "unknown" not in sources
        source = next(iter(sources)) if len(sources) == 1 else "mixed" if sources else "unknown"
        return {"amount": self.total_cost if complete else None, "currency": "USD", "source": source,
                "complete": complete, "calls": len(self.usage), "input_tokens": self.total_input_tokens,
                "output_tokens": self.total_output_tokens, "model_response_seconds": round(self.total_ttft, 3)}

    def summary(self) -> str:
        """Human-readable attribution; estimates never imply a provider charge."""
        details = self.details()
        calls = details["calls"]
        if not calls:
            return "Usage unavailable (no successful model usage captured)"
        labels = {"provider_reported": "Provider-reported cost", "free_model_estimate": "Free-model estimate (not billing)",
                  "estimated": "Estimated cost (not billing)", "mixed": "Mixed measured/estimated cost"}
        cost = f"{labels.get(details['source'], 'Cost')}: {format_cost(details['amount'])}" if details['complete'] else "Cost unknown (provider did not report a charge; no matching price)"
        parts = [cost, f"{calls} LLM call(s)", f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens"]
        avg = self.avg_ttft
        if avg is not None:
            parts.append(f"Model response time: {avg:.2f}s avg")
        return " Β· ".join(parts)

    def reset(self) -> None:
        self.usage.clear()
        self._start_times.clear()


# ─── Error event logging ─────────────────────────────────────────────────--


# ─── Score logging ──────────────────────────────────────────────────────────


def _resolve_langfuse_trace_id(handler: Any) -> Optional[str]:
    """Resolve the current Langfuse trace ID from handler or context.

    Tries, in order:
    1. ``handler.trace_id`` (langfuse v3-style β€” likely None on v4+)
    2. ``handler.last_trace_id`` (langfuse v4+)
    3. ``Langfuse().get_current_trace_id()`` (langfuse v4+, works
       inside ``propagate_attributes`` context)
    """
    if handler is not None:
        try:
            tid = getattr(handler, "trace_id", None)
            if tid:
                return tid
        except Exception:
            pass
        try:
            tid = getattr(handler, "last_trace_id", None)
            if tid:
                return tid
        except Exception:
            pass

    try:
        from opentelemetry import trace
        context = trace.get_current_span().get_span_context()
        if context.is_valid:
            return format(context.trace_id, "032x")
    except Exception:
        pass

    return None


def flush_langfuse() -> None:
    """Flush the shared Langfuse client's pending events once per run.

    In langfuse v4+ ``get_client()`` returns a process-wide singleton; callers
    (e.g. ``main.py`` after the RAGAS block, ``app.py`` after streaming) should
    call this once at the end of a run so queued scores/traces are shipped
    before the process exits β€” instead of flushing inside every
    :func:`log_langfuse_score` call.

    Set ``OCR_OBSERVABILITY_STRICT=1`` to surface flush failures as exceptions.
    """
    if not is_langfuse_enabled():
        return
    try:
        from langfuse import get_client  # v4 singleton β€” one shared client

        get_client().flush()
    except ImportError:
        # Missing SDK degrades gracefully β€” tracing is optional.
        logger.debug("langfuse SDK not installed β€” flush skipped")
    except Exception as exc:
        if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
            raise
        logger.error("Failed to flush Langfuse client: %s", exc)


def log_langfuse_score(
    name: str,
    value: float,
    comment: Optional[str] = None,
    trace_id: Optional[str] = None,
    handler: Optional[Any] = None,
) -> None:
    """Log a numeric score to Langfuse, linked to a specific trace.

    Requires Langfuse to be enabled (keys in environment).  The score is
    associated with a trace by ``trace_id``.  If neither ``trace_id`` nor
    a resolvable handler is provided, the score is logged without a trace
    link (appears in the Scores tab but not on the trace detail page).

    Parameters
    ----------
    name : str
        Score name (e.g. ``"verdict_score"``, ``"findings_count"``).
    value : float
        Numeric score value.
    comment : str or None
        Optional human-readable comment.
    trace_id : str or None
        Explicit trace ID.  If ``None``, attempts to resolve via handler.
    handler : Langfuse CallbackHandler or None
        Langfuse ``CallbackHandler`` from which to extract the trace ID.
    """
    if not is_langfuse_enabled():
        return

    resolved_trace_id = trace_id or _resolve_langfuse_trace_id(handler)
    if not resolved_trace_id:
        logger.warning("Score %s was not logged: no captured trace ID", name)
        return

    # Visibility log: lets you confirm the score will land on the right
    # trace (or spot a None that would create an orphaned score).
    logger.info("Langfuse trace_id resolved: %s", resolved_trace_id)

    try:
        from langfuse import get_client  # v4 singleton β€” one shared client

        lf = get_client()
        kwargs: dict[str, Any] = {
            "name": name,
            "value": value,
        }
        if resolved_trace_id:
            kwargs["trace_id"] = resolved_trace_id
        if comment:
            kwargs["comment"] = comment

        lf.create_score(**kwargs)
        # NOTE: do not flush here β€” flushing once per run via
        # flush_langfuse() at run-end (called by app.py/main.py owners).
    except ImportError:
        # Missing SDK degrades gracefully β€” tracing is optional.
        logger.debug(
            "langfuse SDK not installed β€” score '%s' not logged", name
        )
    except Exception as exc:
        if os.environ.get("OCR_OBSERVABILITY_STRICT") == "1":
            raise
        logger.error(
            "Failed to log Langfuse score '%s'=%.4f (trace_id=%s, comment=%s): %s",
            name, value, resolved_trace_id, comment, exc,
        )


def update_langfuse_trace(
    trace_name: Optional[str] = None,
    tags: Optional[list[str]] = None,
    metadata: Optional[dict[str, Any]] = None,
    trace_id: Optional[str] = None,
    handler: Optional[Any] = None,
) -> None:
    """No-op in langfuse v4+ β€” trace attributes must be set upfront
    via ``propagate_attributes()`` (see :func:`langfuse_trace`).

    In langfuse v4 the trace API no longer supports ``update_trace``.
    Trace-level metadata (name, tags, user_id, session_id, metadata)
    must be provided at trace creation time via ``propagate_attributes``.
    Use :func:`log_langfuse_score` instead for post-hoc annotations
    like verdict score or findings count.
    """
    if resolved_trace_id := (trace_id or _resolve_langfuse_trace_id(handler)):
        logger.debug(
            "update_langfuse_trace is a no-op in langfuse v4 (trace=%s). "
            "Set attributes upfront via langfuse_trace() instead.",
            resolved_trace_id,
        )
    # Dedicated score logging is handled by log_langfuse_score() β€” nothing
    # to do here.


def log_error_to_backends(
    error: Exception,
    context: Optional[dict[str, Any]] = None,
) -> None:
    """Log an error event to whichever observability backend(s) are active.

    For LangSmith: logs via LangChain's callback system (automatic).
    For Langfuse: creates an identifyable error event via the SDK.

    This function primarily logs to ``logger`` with full traceback and
    enriches the log record with context that the tracing backends pick up.

    Parameters
    ----------
    error : Exception
        The exception that occurred.
    context : dict or None
        Additional context about where/when the error happened.
    """
    extras = ""
    if context:
        extras = f" [{', '.join(f'{k}={v}' for k, v in context.items())}]"

    logger.exception(
        "OBSERVABILITY-ERROR%s: %s: %s",
        extras,
        type(error).__name__,
        error,
        exc_info=error,
    )