Spaces:
Running on Zero

File size: 8,066 Bytes
0a96270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Private daily usage aggregates; never retain inputs, outputs or user identities."""

from __future__ import annotations

import errno
import json
import math
import os
import tempfile
import threading
from datetime import datetime, timezone
from pathlib import Path

from scripts.config import MODEL_REGISTRY, TASKS
from scripts.requests import Job


LENGTH_BINS = (
    (128, "1-128"),
    (512, "129-512"),
    (1024, "513-1024"),
    (2048, "1025-2048"),
    (4096, "2049-4096"),
    (10240, "4097-10240"),
)
ERROR_CODES = frozenset({
    "invalid_request", "model_unavailable", "max_records", "max_total_nt",
    "native_context", "max_variants", "variant_span", "max_mask_patterns",
    "max_forward_tokens", "max_attention_cells", "max_gpu_duration",
    "max_masked_sites", "max_variant_chars", "output_storage", "gpu_quota",
    "gpu_runs_limit", "gpu_duration_limit", "queue_full", "gpu_memory", "gpu_timeout",
    "internal_error",
})


def _workload() -> dict:
    return {
        "batches": 0,
        "records": 0,
        "input_nt": 0,
        "variants": 0,
        "masked_sites": 0,
        "length_histogram": {**{label: 0 for _, label in LENGTH_BINS}, ">10240": 0},
    }


def _counter() -> dict:
    return {
        "requests": 0,
        "gpu_calls_attempted": 0,
        "succeeded": 0,
        "rejected": 0,
        "failed": 0,
        "errors": {},
        "requested": _workload(),
        "completed": _workload(),
        "completed_forward_tokens": 0,
        "completed_attention_cells": 0,
        "inference_seconds_sum": 0.0,
        "measured_successful_batches": 0,
        "handler_seconds_sum": 0.0,
    }


def _day(date: str) -> dict:
    return {
        "schema_version": 1,
        "date_utc": date,
        "totals": _counter(),
        "tasks": {task: _counter() for task in TASKS},
        "checkpoints": {
            name: {"requested": _workload(), "completed": _workload()}
            for name in MODEL_REGISTRY
        },
    }


def _add_records(counter: dict, records) -> None:
    if not records:
        return
    counter["batches"] += 1
    for record in records:
        length = len(record.sequence)
        label = next((label for cap, label in LENGTH_BINS if length <= cap), ">10240")
        counter["records"] += 1
        counter["input_nt"] += length
        counter["variants"] += len(record.variants)
        counter["masked_sites"] += len(record.positions)
        counter["length_histogram"][label] += 1


def _seconds(value: float | None) -> float:
    return value if value is not None and math.isfinite(value) and value >= 0 else 0.0


def update_day(stats: dict, task: str, job: Job | None, *, outcome: str,
               code: str | None, gpu_attempted: bool, handler_seconds: float,
               inference_seconds: float | None) -> None:
    """Aggregate validated workloads and outcomes, with a fixed field schema."""

    if task not in TASKS or outcome not in {"succeeded", "rejected", "failed"}:
        raise ValueError("invalid usage event")
    if outcome == "succeeded" and (job is None or not gpu_attempted):
        raise ValueError("successful event requires a valid GPU job")
    if job is not None and job.task != task:
        raise ValueError("usage task mismatch")
    records = job.records if job is not None else ()
    completed = outcome == "succeeded"
    for counter in (stats["totals"], stats["tasks"][task]):
        counter["requests"] += 1
        counter["gpu_calls_attempted"] += int(gpu_attempted)
        counter[outcome] += 1
        counter["handler_seconds_sum"] += _seconds(handler_seconds)
        if not completed:
            error = code if code in ERROR_CODES else "internal_error"
            counter["errors"][error] = counter["errors"].get(error, 0) + 1
        _add_records(counter["requested"], records)
        if completed:
            _add_records(counter["completed"], records)
            counter["completed_forward_tokens"] += job.forward_tokens
            counter["completed_attention_cells"] += job.attention_cells
            if inference_seconds is not None and math.isfinite(inference_seconds) and inference_seconds >= 0:
                counter["inference_seconds_sum"] += inference_seconds
                counter["measured_successful_batches"] += 1

    for name in MODEL_REGISTRY:
        selected = [record for record in records if record.model.name == name]
        entry = stats["checkpoints"][name]
        _add_records(entry["requested"], selected)
        if completed:
            _add_records(entry["completed"], selected)


class UsageStore:
    """Single-writer daily JSON summaries on an explicitly configured volume."""

    def __init__(self, directory: str | None):
        self.root = None
        self._lock = threading.Lock()
        if directory:
            path = Path(directory)
            if not path.is_absolute():
                print("RIBOSPAN usage disabled: RIBOSPAN_STATS_DIR must be absolute.", flush=True)
            else:
                try:
                    self.root = path.resolve()
                except (OSError, RuntimeError):
                    print("RIBOSPAN usage disabled: cannot resolve statistics volume.", flush=True)

    @property
    def blocked_paths(self) -> list[str]:
        # The public Gradio file-serving route must never expose analytics.
        return [str(self.root)] if self.root is not None else []

    def _save(self, path: Path, stats: dict) -> None:
        # Replace a complete snapshot rather than appending to an object-store
        # file. A mount without rename support can use closed-file overwrite.
        data = json.dumps(stats, ensure_ascii=True, indent=2, allow_nan=False) + "\n"
        name = None
        try:
            with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.root,
                                             prefix=".usage-", suffix=".json", delete=False) as handle:
                name = handle.name
                handle.write(data)
            try:
                os.replace(name, path)
            except OSError as exc:
                if exc.errno not in {errno.ENOSYS, errno.EXDEV, errno.EOPNOTSUPP}:
                    raise
                path.write_text(data, encoding="utf-8")
        finally:
            if name is not None:
                try:
                    Path(name).unlink(missing_ok=True)
                except OSError:
                    pass

    def record(self, task: str, job: Job | None, *, outcome: str, code: str | None,
               gpu_attempted: bool, handler_seconds: float,
               inference_seconds: float | None) -> None:
        if self.root is None:
            return
        try:
            # Do not create an unmounted directory and silently claim durable
            # storage. The operator must attach the private bucket first.
            if not self.root.is_dir():
                raise OSError("analytics volume missing")
            date = datetime.now(timezone.utc).date().isoformat()
            path = self.root / f"{date}.json"
            with self._lock:
                try:
                    stats = json.loads(path.read_text(encoding="utf-8"))
                except FileNotFoundError:
                    stats = _day(date)
                if stats.get("schema_version") != 1 or stats.get("date_utc") != date:
                    raise ValueError("unexpected usage schema")
                update_day(stats, task, job, outcome=outcome, code=code,
                           gpu_attempted=gpu_attempted, handler_seconds=handler_seconds,
                           inference_seconds=inference_seconds)
                self._save(path, stats)
        except Exception:
            # Best effort: no payload, exception text, or result is logged,
            # and telemetry failures cannot replace the inference response.
            print("RIBOSPAN usage write failed; check the private statistics volume.", flush=True)


USAGE = UsageStore(os.environ.get("RIBOSPAN_STATS_DIR"))