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 
 
 
 
 
 
 
 
 
 
 
 
dc7c214
ccf1afc
dc7c214
 
 
 
 
 
 
 
 
ccf1afc
dc7c214
 
 
ccf1afc
dc7c214
 
 
 
 
 
ccf1afc
dc7c214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccf1afc
dc7c214
 
 
 
 
 
 
 
 
 
 
 
 
 
ccf1afc
dc7c214
 
ccf1afc
 
 
 
 
 
dc7c214
ccf1afc
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
"""
Permanent session & user context logger.

Lưu vĩnh viễn ngữ cảnh từng phiên và từng user vào dataset HuggingFace ngay khi
có message/event mới — fire-and-forget, robust, không bao giờ block agent.

FIX (anti-hang, bounded single-file-per-session):
  Trước đây mỗi message spawn ra 1 subprocess riêng và upload 1 file riêng
  ``sessions/{date}/{session_id}_{seq}.jsonl``, kèm toàn bộ ``content`` có thể
  rất dài. Với session ngữ cảnh lớn (hàng nghìn message, content tới hàng chục
  MB) điều này tạo hàng nghìn subprocess + hàng nghìn API upload -> Space treo.

  Bản vá này:
    1. Gộp toàn bộ ngữ cảnh session vào MOT file duy nhat
       ``sessions/{date}/{session_id}.jsonl``.
    2. KHONG luu tung message bang subprocess - chi append vao buffer bo nho +
       file local (re, khong block); mot flusher nen dinh ky upload file gop
       bang MOT lan goi ``upload_file``.
    3. Gioi han dung luong luu tru: content message qua dai bi cat gon, va so
       dong luu moi session bi chan (giu cac message gan nhat); cac message cu
       bi loai duoc gop thanh mot dong tom tat ngan gon bao luu ngucanh truoc do.
       Nho do dataset file luon nho -> khong con loi treo, van giu duoc ngucanh
       truoc do de restore/catch-up.
"""

from __future__ import annotations

import json
import logging
import os
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Optional

from huggingface_hub import HfApi, hf_hub_download

logger = logging.getLogger(__name__)

PUBLIC_SESSIONS_DATASET = os.environ.get(
    "ML_INTERN_SESSIONS_DATASET", "bep40/ml-intern-sessions"
)

DEFAULT_LOG_DIR = Path(os.environ.get("ML_INTERN_SESSION_LOG_DIR", "/tmp/session_logs"))

# ---- Bounding knobs: keep dataset small -> no hang ----
FLUSH_INTERVAL = float(os.environ.get("ML_INTERN_FLUSH_INTERVAL", "20"))
MAX_STORED_CONTENT = int(os.environ.get("ML_INTERN_MAX_CONTENT", "12000"))
MAX_STORED_ROWS = int(os.environ.get("ML_INTERN_MAX_ROWS", "400"))
MAX_SUMMARY_CHARS = int(os.environ.get("ML_INTERN_MAX_SUMMARY", "4000"))


def _now_iso() -> str:
    return datetime.now().astimezone().isoformat()


def _get_hf_token() -> Optional[str]:
    return (
        os.environ.get("HF_TOKEN")
        or os.environ.get("_ML_INTERN_PERSONAL_TOKEN")
        or os.environ.get("HF_SESSION_UPLOAD_TOKEN")
        or os.environ.get("HF_ADMIN_TOKEN")
    )


def _dataset_card_readme() -> str:
    return """---
pretty_name: "ML Intern Session Context"
language:
- en
license: other
task_categories:
- text-generation
tags:
- ml-intern
- session-traces
- conversation
- agent-traces
configs:
- config_name: default
  data_files:
  - split: train
    path: "sessions/**/*.jsonl"
---

# ML Intern Session Context

**Luu tru vinh vien ngucanh tung phien va tung user.**

Moi session duoc gop thanh MOT file `sessions/{date}/{session_id}.jsonl`.
Noi dung message qua dai duoc cat gon va so dong moi session duoc chan (cac
message cu gop thanh dong tom tat) de tranh treo Space, nhung van bao luu ngucanh
truoc do cho restore/catch-up.
"""


# ---- In-process aggregated buffer + throttled flusher ----

_lock = threading.Lock()
_session_buffers: dict[str, list[dict]] = {}
_session_hf_user: dict[str, Optional[str]] = {}
_dirty: set[str] = set()
_last_upload: dict[str, float] = {}
_flusher_started = False


def _ensure_flusher() -> None:
    global _flusher_started
    if _flusher_started:
        return
    with _lock:
        if _flusher_started:
            return
        _flusher_started = True
    t = threading.Thread(target=_flusher_loop, name="session-flusher", daemon=True)
    t.start()


def _flusher_loop() -> None:
    while True:
        time.sleep(FLUSH_INTERVAL)
        try:
            _flush_once()
        except Exception as e:
            logger.debug("Session flusher error: %s", e)


def _truncate_text(s: str, limit: int) -> str:
    s = s if isinstance(s, str) else (str(s) if s is not None else "")
    if len(s) <= limit:
        return s
    head = s[: max(limit // 2, 1)]
    tail = s[-max(limit // 2, 1):]
    return f"{head} ...[{len(s)} chars trimmed]... {tail}"


def _build_condensed_summary(dropped: list[dict]) -> str:
    parts = []
    for r in dropped:
        role = r.get("role", "")
        content = (r.get("content") or "")
        if isinstance(content, str) and content.strip():
            c = content.strip().replace("\n", " ")
            if len(c) > 300:
                c = c[:150] + " ... " + c[-80:]
            parts.append(f"[{role}] {c}")
    text = " | ".join(parts)
    if len(text) > MAX_SUMMARY_CHARS:
        text = text[:MAX_SUMMARY_CHARS] + " ...(summary truncated)"
    return text


def _bound_rows(rows: list[dict]) -> None:
    for r in rows:
        if r.get("role") == "event" and r.get("event_type") == "context_summary":
            continue
        r["content"] = _truncate_text(r.get("content", ""), MAX_STORED_CONTENT)

    if len(rows) <= MAX_STORED_ROWS:
        return

    keep = rows[-(MAX_STORED_ROWS - 1):]
    dropped = rows[: -(MAX_STORED_ROWS - 1)]
    summary_text = _build_condensed_summary(dropped)
    summary_row = {
        "session_id": rows[0].get("session_id", ""),
        "user_id": rows[0].get("user_id", ""),
        "model_name": rows[0].get("model_name", ""),
        "timestamp": rows[0].get("timestamp", ""),
        "role": "system",
        "content": "CONTEXT SUMMARY (earlier conversation, preserved for restore): " + summary_text,
        "event_type": "context_summary",
        "seq": dropped[0].get("seq", 0),
        "extra": "{}",
    }
    rows[:] = [summary_row] + keep


def _flush_once() -> None:
    now = time.time()
    candidates: list[str] = []
    with _lock:
        for sid in list(_dirty):
            if now - _last_upload.get(sid, 0) >= FLUSH_INTERVAL:
                _dirty.discard(sid)
                candidates.append(sid)
    for sid in candidates:
        try:
            _upload_session_aggregate(sid)
        except Exception as e:
            logger.debug("Session %s upload failed: %s", sid, e)
            with _lock:
                _dirty.add(sid)
        with _lock:
            _last_upload[sid] = time.time()


def _upload_session_aggregate(session_id: str) -> None:
    with _lock:
        rows = list(_session_buffers.get(session_id, []))
        hf_user = _session_hf_user.get(session_id)
    if not rows:
        return

    rows = list(rows)
    _bound_rows(rows)

    content = "\n".join(json.dumps(r, default=str) for r in rows) + "\n"
    date_str = rows[0].get("timestamp", "")[:10] or datetime.now().strftime("%Y-%m-%d")
    path_in_repo = f"sessions/{date_str}/{session_id}.jsonl"

    token = _get_hf_token()
    if not token:
        return

    api = HfApi()
    try:
        api.upload_file(
            path_or_fileobj=content.encode("utf-8"),
            path_in_repo=path_in_repo,
            repo_id=PUBLIC_SESSIONS_DATASET,
            repo_type="dataset",
            token=token,
            commit_message=f"Update session {session_id[:8]} context ({len(rows)} msgs)",
        )
    except Exception as e:
        logger.debug("Public session upload failed: %s", e)

    if hf_user and hf_user != "dev":
        try:
            api.create_repo(
                repo_id=f"{hf_user}/ml-intern-sessions",
                repo_type="dataset",
                private=True,
                token=token,
                exist_ok=True,
            )
            api.upload_file(
                path_or_fileobj=content.encode("utf-8"),
                path_in_repo=path_in_repo,
                repo_id=f"{hf_user}/ml-intern-sessions",
                repo_type="dataset",
                token=token,
                commit_message=f"Update session {session_id[:8]} context ({len(rows)} msgs)",
            )
        except Exception as e:
            logger.debug("Personal session upload failed: %s", e)


def _append_to_local_log(
    session_id: str,
    user_id: str,
    model_name: str,
    role: str,
    content: str,
    event_type: str,
    seq: int,
    extra: dict | None = None,
    directory: str = str(DEFAULT_LOG_DIR),
) -> Optional[str]:
    try:
        log_dir = Path(directory)
        log_dir.mkdir(parents=True, exist_ok=True)
        row = {
            "session_id": session_id,
            "user_id": user_id,
            "model_name": model_name,
            "timestamp": _now_iso(),
            "role": role,
            "content": content,
            "event_type": event_type,
            "seq": seq,
            "extra": json.dumps(extra) if extra else "{}",
        }
        date_str = datetime.now().strftime("%Y-%m-%d")
        filename = f"session_{session_id}_{date_str}.jsonl"
        filepath = log_dir / filename
        with open(filepath, "a") as f:
            f.write(json.dumps(row, default=str) + "\n")
        return str(filepath)
    except Exception as e:
        logger.debug("Local log write failed: %s", e)
        return None


# ---- Dataset reader: per-file scan ----

_file_list_cache: list[str] | None = None
_file_list_cache_time: float = 0


def _list_dataset_files() -> list[str]:
    global _file_list_cache, _file_list_cache_time
    now = time.time()
    if _file_list_cache is not None and (now - _file_list_cache_time) < 60:
        return _file_list_cache
    try:
        api = HfApi(token=_get_hf_token())
        files = api.list_repo_files(PUBLIC_SESSIONS_DATASET, repo_type="dataset")
        _file_list_cache = [f for f in files if f.endswith(".jsonl")]
        _file_list_cache_time = now
    except Exception as e:
        logger.warning("Failed to list dataset files: %s", e)
        _file_list_cache = []
        _file_list_cache_time = now
    return _file_list_cache


def _normalize_row(row: dict) -> dict | None:
    if not isinstance(row, dict):
        return None

    if "session_id" in row and "role" in row:
        return row

    if "type" in row and "message" in row:
        session_id = row.get("sessionId") or row.get("session_id") or ""
        if not session_id:
            return None
        msg = row.get("message")
        role = row.get("type", "unknown")
        content_text = ""
        model_name = ""
        if isinstance(msg, dict):
            role = msg.get("role", role)
            content_val = msg.get("content", "")
            model_name = msg.get("model", "")
            if isinstance(content_val, str):
                content_text = content_val
            elif isinstance(content_val, list):
                parts = []
                for block in content_val:
                    if isinstance(block, dict):
                        t = block.get("text") or block.get("content")
                        if isinstance(t, str):
                            parts.append(t)
                    elif isinstance(block, str):
                        parts.append(block)
                content_text = " ".join(parts)
            elif content_val is None:
                content_text = ""
        return {
            "session_id": session_id,
            "user_id": "",
            "model_name": model_name,
            "timestamp": row.get("timestamp", ""),
            "role": role,
            "content": content_text,
            "event_type": row.get("type", "message"),
            "seq": 0,
            "extra": "{}",
        }

    return None


def _read_jsonl_file(file_path: str) -> list[dict]:
    try:
        local = hf_hub_download(
            PUBLIC_SESSIONS_DATASET,
            file_path,
            repo_type="dataset",
            token=_get_hf_token(),
        )
        rows: list[dict] = []
        with open(local, encoding="utf-8", errors="replace") as fh:
            for line in fh:
                line = line.strip()
                if not line:
                    continue
                try:
                    row = json.loads(line)
                    normalized = _normalize_row(row)
                    if normalized is not None:
                        rows.append(normalized)
                except json.JSONDecodeError:
                    continue
        return rows
    except Exception as e:
        logger.debug("Failed to read %s: %s", file_path, e)
        return []


def load_session_history(session_id: str) -> list[dict]:
    try:
        all_files = _list_dataset_files()
        matching = [f for f in all_files if session_id in os.path.basename(f)]
        rows: list[dict] = []
        for f in matching:
            for row in _read_jsonl_file(f):
                if row.get("session_id") == session_id:
                    rows.append(row)
        rows.sort(key=lambda r: (r.get("seq", 0), r.get("timestamp", "")))
        return rows
    except Exception as e:
        import traceback
        logger.warning(
            "Failed to load session history: %s\n%s",
            e,
            traceback.format_exc(),
        )
        return []


def get_user_sessions(user_id: str, limit: int = 50) -> list[dict]:
    sessions: dict[str, dict] = {}
    for f in _list_dataset_files():
        for row in _read_jsonl_file(f):
            if row.get("user_id") == user_id:
                sid = row.get("session_id")
                if sid and sid not in sessions:
                    sessions[sid] = {
                        "session_id": sid,
                        "user_id": user_id,
                        "model_name": row.get("model_name"),
                        "last_timestamp": row.get("timestamp"),
                        "message_count": 0,
                    }
                sessions[sid]["message_count"] += 1

    result = list(sessions.values())
    result.sort(key=lambda s: s.get("last_timestamp", ""), reverse=True)
    return result[:limit]


# ---- Public API ----


def log_message(
    session_id: str,
    user_id: str,
    model_name: str,
    role: str,
    content: str,
    event_type: str = "message",
    seq: int = 0,
    extra: dict | None = None,
    hf_user: str | None = None,
) -> None:
    """Log a single message/event permanently to dataset. Fire-and-forget."""
    row_data = {
        "session_id": session_id,
        "user_id": user_id,
        "model_name": model_name,
        "timestamp": _now_iso(),
        "role": role,
        "content": content,
        "event_type": event_type,
        "seq": seq,
        "extra": json.dumps(extra) if extra else "{}",
    }

    _append_to_local_log(
        session_id=session_id,
        user_id=user_id,
        model_name=model_name,
        role=role,
        content=content,
        event_type=event_type,
        seq=seq,
        extra=extra,
    )

    with _lock:
        _session_buffers.setdefault(session_id, []).append(row_data)
        _session_hf_user[session_id] = hf_user
        _dirty.add(session_id)

    _ensure_flusher()


def log_trajectory(
    trajectory: dict,
    user_id: str,
    hf_user: str | None = None,
    hf_token: str | None = None,
    private: bool = False,
) -> Optional[str]:
    """Upload complete session trajectory to dataset (final flush, bounded)."""
    session_id = trajectory.get("session_id", "unknown")
    model_name = trajectory.get("model_name", "")
    messages = trajectory.get("messages", [])
    events = trajectory.get("events", [])

    log_dir = Path(str(DEFAULT_LOG_DIR))
    log_dir.mkdir(parents=True, exist_ok=True)
    date_str = datetime.now().strftime("%Y-%m-%d")
    filepath = log_dir / f"session_{session_id}_{date_str}.jsonl"

    rows: list[dict] = []
    with open(filepath, "w") as f:
        for msg in messages:
            row = {
                "session_id": session_id,
                "user_id": user_id,
                "model_name": model_name,
                "timestamp": msg.get("timestamp") or _now_iso(),
                "role": msg.get("role", "unknown"),
                "content": msg.get("content", ""),
                "event_type": "message",
                "seq": msg.get("seq", 0),
                "extra": json.dumps({
                    "tool_calls": msg.get("tool_calls"),
                    "tool_call_id": msg.get("tool_call_id"),
                }) if any(k in msg for k in ("tool_calls", "tool_call_id")) else "{}",
            }
            rows.append(row)
            f.write(json.dumps(row, default=str) + "\n")

        for event in events:
            row = {
                "session_id": session_id,
                "user_id": user_id,
                "model_name": model_name,
                "timestamp": event.get("timestamp", _now_iso()),
                "role": "event",
                "content": json.dumps(event.get("data", {})),
                "event_type": event.get("event_type", "unknown"),
                "seq": event.get("seq", 0),
                "extra": "{}",
            }
            rows.append(row)
            f.write(json.dumps(row, default=str) + "\n")

    with _lock:
        _session_buffers[session_id] = rows
        _session_hf_user[session_id] = hf_user
        _dirty.add(session_id)

    _ensure_flusher()

    return str(filepath)