kaggle-shell-mcp 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kaggle_mcp/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """kaggle-shell-mcp: Headless 12h Kaggle GPU Worker & Remote Terminal MCP Server."""
2
+
3
+ __app_name__ = "kaggle-shell-mcp"
4
+ __version__ = "0.2.0"
@@ -0,0 +1,124 @@
1
+ """Hardware accelerator resolution and Kaggle runtime lifetime caps."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ MAX_GPU_LIFETIME_SEC = 42000 # 11h 40m safe exit before Kaggle 12h GPU/CPU reaper
9
+ GPU_DRAIN_AT_SEC = 41700 # 11h 35m SIGTERM checkpoint window
10
+
11
+ MAX_TPU_LIFETIME_SEC = 31200 # 8h 40m safe exit before Kaggle 9h TPU reaper
12
+ TPU_DRAIN_AT_SEC = 30900 # 8h 35m SIGTERM checkpoint window
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class AcceleratorSpec:
17
+ enable_gpu: bool
18
+ enable_tpu: bool
19
+ machine_shape: str | None
20
+ max_lifetime_sec: int = MAX_GPU_LIFETIME_SEC
21
+ drain_at_sec: int = GPU_DRAIN_AT_SEC
22
+
23
+ @property
24
+ def label(self) -> str:
25
+ if self.machine_shape:
26
+ return self.machine_shape
27
+ if self.enable_tpu:
28
+ return "TPU"
29
+ if self.enable_gpu:
30
+ return "GPU"
31
+ return "CPU"
32
+
33
+
34
+ _GPU_ALIASES: dict[str, str] = {
35
+ "t4": "NvidiaTeslaT4",
36
+ "t4x2": "NvidiaTeslaT4",
37
+ "teslat4": "NvidiaTeslaT4",
38
+ "nvidiateslat4": "NvidiaTeslaT4",
39
+ "l4": "NvidiaL4",
40
+ "l4x1": "NvidiaL4",
41
+ "nvidial4": "NvidiaL4",
42
+ "nvidial4x1": "NvidiaL4",
43
+ "l4x4": "NvidiaL4x4",
44
+ "nvidial4x4": "NvidiaL4x4",
45
+ "rtx6000": "NvidiaRtxPro6000",
46
+ "rtxpro6000": "NvidiaRtxPro6000",
47
+ "pro6000": "NvidiaRtxPro6000",
48
+ "nvidiartxpro6000": "NvidiaRtxPro6000",
49
+ "h100": "NvidiaH100",
50
+ "nvidiah100": "NvidiaH100",
51
+ "p100": "NvidiaTeslaP100",
52
+ "nvidiateslap100": "NvidiaTeslaP100",
53
+ }
54
+
55
+ _TPU_ALIASES: dict[str, str] = {
56
+ "tpu": "TpuV5E8",
57
+ "tpuv5e8": "TpuV5E8",
58
+ "v5e8": "TpuV5E8",
59
+ "tpuvmv5e8": "TpuV5E8",
60
+ "tpuv6e8": "TpuV6E8",
61
+ "v6e8": "TpuV6E8",
62
+ }
63
+
64
+ _CPU_ALIASES = {"none", "cpu", "off", "false", "no"}
65
+
66
+
67
+ def resolve_accelerator(accelerator: str | None = None, gpu: bool = True) -> AcceleratorSpec:
68
+ """Normalize user/agent accelerator aliases into Kaggle kernel metadata flags."""
69
+ raw = (accelerator or "").strip()
70
+ norm = re.sub(r"[\s_-]+", "", raw.lower())
71
+
72
+ if norm in _CPU_ALIASES or (not raw and not gpu):
73
+ return AcceleratorSpec(
74
+ enable_gpu=False,
75
+ enable_tpu=False,
76
+ machine_shape=None,
77
+ max_lifetime_sec=MAX_GPU_LIFETIME_SEC,
78
+ drain_at_sec=GPU_DRAIN_AT_SEC,
79
+ )
80
+
81
+ if not raw and gpu:
82
+ return AcceleratorSpec(
83
+ enable_gpu=True,
84
+ enable_tpu=False,
85
+ machine_shape="NvidiaTeslaT4",
86
+ max_lifetime_sec=MAX_GPU_LIFETIME_SEC,
87
+ drain_at_sec=GPU_DRAIN_AT_SEC,
88
+ )
89
+
90
+ if norm in _TPU_ALIASES:
91
+ return AcceleratorSpec(
92
+ enable_gpu=False,
93
+ enable_tpu=True,
94
+ machine_shape=_TPU_ALIASES[norm],
95
+ max_lifetime_sec=MAX_TPU_LIFETIME_SEC,
96
+ drain_at_sec=TPU_DRAIN_AT_SEC,
97
+ )
98
+
99
+ if norm in _GPU_ALIASES:
100
+ return AcceleratorSpec(
101
+ enable_gpu=True,
102
+ enable_tpu=False,
103
+ machine_shape=_GPU_ALIASES[norm],
104
+ max_lifetime_sec=MAX_GPU_LIFETIME_SEC,
105
+ drain_at_sec=GPU_DRAIN_AT_SEC,
106
+ )
107
+
108
+ if norm.startswith("tpu"):
109
+ return AcceleratorSpec(
110
+ enable_gpu=False,
111
+ enable_tpu=True,
112
+ machine_shape=raw,
113
+ max_lifetime_sec=MAX_TPU_LIFETIME_SEC,
114
+ drain_at_sec=TPU_DRAIN_AT_SEC,
115
+ )
116
+
117
+ # Passthrough unknown future GPU shapes (e.g. NvidiaB200) without requiring code updates
118
+ return AcceleratorSpec(
119
+ enable_gpu=True,
120
+ enable_tpu=False,
121
+ machine_shape=raw,
122
+ max_lifetime_sec=MAX_GPU_LIFETIME_SEC,
123
+ drain_at_sec=GPU_DRAIN_AT_SEC,
124
+ )
kaggle_mcp/batch.py ADDED
@@ -0,0 +1,554 @@
1
+ """Offline Competition Runner: Linux wheelhouse builder, code dataset bundler & bounded Host SSE logs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import queue
8
+ import re
9
+ import secrets
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from .accelerators import resolve_accelerator
19
+ from .config import (
20
+ STATE_DIR,
21
+ ActiveSession,
22
+ Settings,
23
+ load_active_session,
24
+ normalize_slot,
25
+ save_active_session,
26
+ )
27
+ from .launcher import (
28
+ TERMINAL_KERNEL_STATUSES,
29
+ get_kaggle_api,
30
+ get_kernel_status,
31
+ normalize_str_list,
32
+ protect_stdout,
33
+ validate_push_response,
34
+ )
35
+ from .sync import pack_tar_gz
36
+
37
+ _ANSI_CURSOR_RE = re.compile(r"\x1b\[[0-9;?]*[ABCDEFGHJKSTfhlm]")
38
+
39
+ OFFLINE_RUNNER_TEMPLATE = '''#!/usr/bin/env python3
40
+ """Offline Kaggle Competition Runner generated by kaggle-shell-mcp."""
41
+
42
+ import base64
43
+ import io
44
+ import json
45
+ import os
46
+ import signal
47
+ import subprocess
48
+ import sys
49
+ import tarfile
50
+ import threading
51
+ import time
52
+ from pathlib import Path
53
+
54
+ CFG = json.loads(base64.b64decode("__BATCH_CONFIG_B64__".encode("ascii")).decode("utf-8"))
55
+ COMMAND = CFG["command"]
56
+ INLINE_BUNDLE_B64 = CFG.get("inline_bundle_b64", "")
57
+ CODE_DS_SLUG = CFG.get("code_dataset_slug", "")
58
+ TOP_ENTRY = CFG.get("top_entry", "")
59
+ WHEEL_SLUGS = CFG.get("wheel_slugs", [])
60
+ MAX_LIFETIME_SEC = int(CFG.get("max_lifetime_sec", 42000))
61
+ DRAIN_AT_SEC = int(CFG.get("drain_at_sec", 41700))
62
+
63
+ os.environ["PYTHONUNBUFFERED"] = "1"
64
+ os.environ["KGSH_OUTPUT_DIR"] = "/kaggle/working"
65
+
66
+
67
+ def install_offline_wheels() -> None:
68
+ input_root = Path("/kaggle/input")
69
+ if not input_root.exists() or not WHEEL_SLUGS:
70
+ return
71
+ wheel_dirs: list[Path] = []
72
+ for slug in WHEEL_SLUGS:
73
+ for candidate in [input_root / slug, *input_root.glob(f"*/{slug}"), *input_root.glob(f"*/*/{slug}")]:
74
+ if candidate.is_dir() and candidate not in wheel_dirs:
75
+ wheel_dirs.append(candidate)
76
+ for wdir in wheel_dirs:
77
+ whls = sorted(str(p) for p in wdir.rglob("*.whl"))
78
+ if not whls:
79
+ continue
80
+ print(f"[kgsh-batch] installing {len(whls)} offline wheels from {wdir}...", flush=True)
81
+ subprocess.run(
82
+ [sys.executable, "-m", "pip", "install", "--no-index", f"--find-links={wdir}", *whls],
83
+ check=True,
84
+ )
85
+
86
+
87
+ def prepare_workspace() -> Path:
88
+ raw_tar: bytes | None = None
89
+ if INLINE_BUNDLE_B64:
90
+ raw_tar = base64.b64decode(INLINE_BUNDLE_B64.encode("ascii"))
91
+ elif CODE_DS_SLUG:
92
+ matches = list(Path("/kaggle/input").rglob("bundle.kgsh"))
93
+ if not matches:
94
+ raise FileNotFoundError(f"Code archive bundle.kgsh not found under /kaggle/input (slug={CODE_DS_SLUG})")
95
+ raw_tar = matches[0].read_bytes()
96
+ else:
97
+ return Path("/kaggle/working")
98
+
99
+ work_root = Path("/tmp/kgsh_batch_work")
100
+ work_root.mkdir(parents=True, exist_ok=True)
101
+ with tarfile.open(fileobj=io.BytesIO(raw_tar), mode="r:gz") as tf:
102
+ try:
103
+ tf.extractall(path=work_root, filter="data")
104
+ except TypeError:
105
+ tf.extractall(path=work_root)
106
+
107
+ if TOP_ENTRY:
108
+ candidate = work_root / TOP_ENTRY
109
+ if candidate.is_dir():
110
+ return candidate
111
+ return work_root
112
+
113
+
114
+ def main() -> int:
115
+ t0 = time.monotonic()
116
+ install_offline_wheels()
117
+ cwd = prepare_workspace()
118
+ print(f"[kgsh-batch] starting command in {cwd}: {COMMAND}", flush=True)
119
+
120
+ proc = subprocess.Popen(
121
+ ["/bin/bash", "-c", COMMAND],
122
+ cwd=str(cwd),
123
+ env=os.environ.copy(),
124
+ start_new_session=True,
125
+ )
126
+
127
+ drained = False
128
+ while proc.poll() is None:
129
+ elapsed = time.monotonic() - t0
130
+ if not drained and elapsed >= DRAIN_AT_SEC:
131
+ drained = True
132
+ print("[kgsh-batch] safe drain window reached; sending SIGTERM to flush checkpoints...", flush=True)
133
+ try:
134
+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
135
+ except ProcessLookupError:
136
+ pass
137
+ if elapsed >= MAX_LIFETIME_SEC:
138
+ print("[kgsh-batch] max safe lifetime reached; terminating cleanly (0) to preserve /kaggle/working.", flush=True)
139
+ try:
140
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
141
+ except ProcessLookupError:
142
+ pass
143
+ return 0
144
+ time.sleep(2.0)
145
+
146
+ rc = proc.returncode or 0
147
+ print(f"[kgsh-batch] finished with exit_code={rc} in {time.monotonic() - t0:.1f}s", flush=True)
148
+ return rc
149
+
150
+
151
+ if __name__ == "__main__":
152
+ sys.exit(main())
153
+ '''
154
+
155
+
156
+ def clean_log_text(text: str) -> str:
157
+ text = text.replace("\r\n", "\n")
158
+ out: list[str] = []
159
+ for raw in text.split("\n"):
160
+ if "\r" in raw:
161
+ segs = [s for s in raw.split("\r") if s != ""]
162
+ raw = segs[-1] if segs else ""
163
+ out.append(_ANSI_CURSOR_RE.sub("", raw))
164
+ return "\n".join(out)
165
+
166
+
167
+ def _upsert_private_dataset(api: Any, dataset_ref: str, folder: Path, notes: str) -> bool:
168
+ """Create or version-bump a private Kaggle dataset. Returns True if newly created."""
169
+ slug = dataset_ref.split("/")[-1]
170
+ meta = {
171
+ "title": slug,
172
+ "id": dataset_ref,
173
+ "licenses": [{"name": "CC0-1.0"}],
174
+ }
175
+ (folder / "dataset-metadata.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
176
+
177
+ exists = False
178
+ try:
179
+ with protect_stdout():
180
+ api.dataset_list_files(dataset_ref)
181
+ exists = True
182
+ except Exception:
183
+ exists = False
184
+
185
+ with protect_stdout():
186
+ if exists:
187
+ api.dataset_create_version(
188
+ folder=str(folder),
189
+ version_notes=notes,
190
+ quiet=True,
191
+ convert_to_csv=False,
192
+ dir_mode="skip",
193
+ )
194
+ return False
195
+ api.dataset_create_new(
196
+ folder=str(folder),
197
+ public=False,
198
+ quiet=True,
199
+ convert_to_csv=False,
200
+ dir_mode="skip",
201
+ )
202
+ return True
203
+
204
+
205
+ def build_wheelhouse(
206
+ settings: Settings,
207
+ packages: str | list[str],
208
+ slug: str = "wheels",
209
+ python_version: str = "312",
210
+ ) -> dict[str, Any]:
211
+ """Download Linux x86_64 binary wheels locally and publish to a private Kaggle Dataset."""
212
+ pkg_list = normalize_str_list(packages)
213
+ if not pkg_list:
214
+ raise ValueError("Provide at least one package name for `kaggle_wheelhouse`.")
215
+
216
+ clean_slug = normalize_slot(slug)
217
+ ds_slug = "kgsh-wheels" if clean_slug == "wheels" else f"kgsh-wheels-{clean_slug}"
218
+ ds_ref = f"{settings.kaggle_username}/{ds_slug}"
219
+ py_ver = python_version.replace(".", "").strip() or "312"
220
+
221
+ with tempfile.TemporaryDirectory(prefix="kgsh_wheels_") as tmp:
222
+ tmp_p = Path(tmp)
223
+ cmd = [
224
+ sys.executable,
225
+ "-m",
226
+ "pip",
227
+ "download",
228
+ "--dest",
229
+ str(tmp_p),
230
+ "--platform",
231
+ "manylinux2014_x86_64",
232
+ "--platform",
233
+ "manylinux_2_28_x86_64",
234
+ "--python-version",
235
+ py_ver,
236
+ "--implementation",
237
+ "cp",
238
+ "--abi",
239
+ f"cp{py_ver}",
240
+ "--only-binary=:all:",
241
+ *pkg_list,
242
+ ]
243
+ res = subprocess.run(cmd, capture_output=True, text=True, check=False)
244
+ if res.returncode != 0:
245
+ raise RuntimeError(
246
+ f"pip download failed (exit {res.returncode}):\n{(res.stderr or res.stdout)[-1500:]}"
247
+ )
248
+
249
+ wheels = sorted(tmp_p.glob("*.whl"))
250
+ total_mb = round(sum(w.stat().st_size for w in wheels) / (1024 * 1024), 2)
251
+
252
+ api = get_kaggle_api(settings)
253
+ created = _upsert_private_dataset(api, ds_ref, tmp_p, notes=f"wheels:{','.join(pkg_list)[:60]}")
254
+
255
+ return {
256
+ "dataset_ref": ds_ref,
257
+ "created_new": created,
258
+ "python_abi": f"cp{py_ver}-manylinux_x86_64",
259
+ "wheel_count": len(wheels),
260
+ "total_mb": total_mb,
261
+ "wheels": [w.name for w in wheels],
262
+ }
263
+
264
+
265
+ def submit_offline_batch(
266
+ settings: Settings,
267
+ command: str,
268
+ local_path: str = "",
269
+ *,
270
+ slot: str = "batch-1",
271
+ accelerator: str = "NvidiaTeslaT4",
272
+ competition: str | list[str] | None = None,
273
+ enable_internet: bool = False,
274
+ wheel_datasets: str | list[str] | None = None,
275
+ mount_datasets: str | list[str] | None = None,
276
+ mount_models: str | list[str] | None = None,
277
+ ) -> dict[str, Any]:
278
+ """Bundle local code into a private Dataset and push a batch kernel (supports L4x4 / RTX Pro 6000 offline)."""
279
+ s = normalize_slot(slot)
280
+ acc_spec = resolve_accelerator(accelerator, gpu=True)
281
+ api = get_kaggle_api(settings)
282
+
283
+ comp_list = normalize_str_list(competition)
284
+ wheel_ds_list = normalize_str_list(wheel_datasets)
285
+ extra_ds_list = normalize_str_list(mount_datasets)
286
+ model_list = normalize_str_list(mount_models)
287
+
288
+ code_ds_slug = ""
289
+ code_ds_ref = ""
290
+ inline_bundle_b64 = ""
291
+ top_entry = ""
292
+
293
+ if local_path and local_path.strip():
294
+ src_p = Path(local_path).expanduser().resolve()
295
+ tar_bytes = pack_tar_gz(src_p)
296
+ top_entry = src_p.name if src_p.is_dir() else ""
297
+
298
+ if len(tar_bytes) <= 512 * 1024:
299
+ # Embed <=512KB source bundles directly inside the script: 0 dataset lag, 100% atomic!
300
+ inline_bundle_b64 = base64.b64encode(tar_bytes).decode("ascii")
301
+ else:
302
+ # Use .kgsh extension so Kaggle Dataset ingestion never auto-extracts or strips the archive
303
+ code_ds_slug = f"kgsh-code-{s}"
304
+ code_ds_ref = f"{settings.kaggle_username}/{code_ds_slug}"
305
+ with tempfile.TemporaryDirectory(prefix=f"kgsh_code_{s}_") as tmp:
306
+ tmp_p = Path(tmp)
307
+ (tmp_p / "bundle.kgsh").write_bytes(tar_bytes)
308
+ _upsert_private_dataset(api, code_ds_ref, tmp_p, notes=f"batch:{s}")
309
+
310
+ # Wait until Kaggle finishes indexing bundle.kgsh before attaching to kernel
311
+ for _ in range(12):
312
+ time.sleep(3.0)
313
+ try:
314
+ with protect_stdout():
315
+ flist = api.dataset_list_files(code_ds_ref)
316
+ fnames = [getattr(f, "name", str(f)) for f in getattr(flist, "files", [])]
317
+ if any("bundle.kgsh" in fn for fn in fnames):
318
+ break
319
+ except Exception:
320
+ continue
321
+
322
+ all_datasets: list[str] = []
323
+ for ds in ([code_ds_ref] if code_ds_ref else []) + wheel_ds_list + extra_ds_list:
324
+ if ds and ds not in all_datasets:
325
+ all_datasets.append(ds)
326
+
327
+ wheel_slugs = [d.split("/")[-1] for d in wheel_ds_list if d]
328
+ batch_cfg = {
329
+ "command": command,
330
+ "inline_bundle_b64": inline_bundle_b64,
331
+ "code_dataset_slug": code_ds_slug,
332
+ "top_entry": top_entry,
333
+ "wheel_slugs": wheel_slugs,
334
+ "max_lifetime_sec": acc_spec.max_lifetime_sec,
335
+ "drain_at_sec": acc_spec.drain_at_sec,
336
+ }
337
+ b64_cfg = base64.b64encode(json.dumps(batch_cfg).encode("utf-8")).decode("ascii")
338
+ runner_src = OFFLINE_RUNNER_TEMPLATE.replace("__BATCH_CONFIG_B64__", b64_cfg)
339
+
340
+ kernel_ref = settings.kernel_ref_for_slot(s, mode="batch")
341
+ kernel_slug = settings.kernel_slug_for_slot(s, mode="batch")
342
+ bundle_dir = STATE_DIR / f"build_batch_{s}"
343
+ bundle_dir.mkdir(parents=True, exist_ok=True)
344
+ (bundle_dir / "offline_runner.py").write_text(runner_src, encoding="utf-8")
345
+
346
+ kernel_meta: dict[str, Any] = {
347
+ "id": kernel_ref,
348
+ "title": kernel_slug,
349
+ "code_file": "offline_runner.py",
350
+ "language": "python",
351
+ "kernel_type": "script",
352
+ "is_private": True,
353
+ "enable_gpu": acc_spec.enable_gpu,
354
+ "enable_tpu": acc_spec.enable_tpu,
355
+ "enable_internet": bool(enable_internet),
356
+ "dataset_sources": all_datasets,
357
+ "competition_sources": comp_list,
358
+ "kernel_sources": [],
359
+ "model_sources": model_list,
360
+ }
361
+ if acc_spec.machine_shape:
362
+ kernel_meta["machine_shape"] = acc_spec.machine_shape
363
+
364
+ (bundle_dir / "kernel-metadata.json").write_text(
365
+ json.dumps(kernel_meta, indent=2),
366
+ encoding="utf-8",
367
+ )
368
+
369
+ with protect_stdout():
370
+ push_resp = api.kernels_push(str(bundle_dir), acc=acc_spec.machine_shape)
371
+ version_number = validate_push_response(push_resp)
372
+
373
+ sess = ActiveSession(
374
+ session_id=f"batch_{secrets.token_hex(8)}",
375
+ kernel_ref=kernel_ref,
376
+ created_at=time.time(),
377
+ slot=s,
378
+ mode="batch",
379
+ accelerator=acc_spec.label,
380
+ version_number=version_number,
381
+ competition=",".join(comp_list),
382
+ enable_internet=bool(enable_internet),
383
+ )
384
+ save_active_session(sess, slot=s)
385
+
386
+ return {
387
+ "slot": s,
388
+ "mode": "batch",
389
+ "kernel_ref": kernel_ref,
390
+ "version_number": version_number,
391
+ "accelerator": acc_spec.label,
392
+ "enable_internet": bool(enable_internet),
393
+ "code_dataset": code_ds_ref or None,
394
+ "attached_datasets": all_datasets,
395
+ "competition_sources": comp_list,
396
+ "model_sources": model_list,
397
+ "next_step": f"Theo dõi tiến độ & đọc live log qua `kaggle_batch_logs(slot='{s}')`.",
398
+ }
399
+
400
+
401
+ def _extract_event_text(ev: Any) -> str:
402
+ if isinstance(ev, str):
403
+ raw = ev
404
+ elif isinstance(ev, dict):
405
+ raw = str(ev.get("data", ""))
406
+ else:
407
+ raw = str(ev)
408
+
409
+ stripped = raw.strip()
410
+ if stripped.startswith("{") and stripped.endswith("}"):
411
+ try:
412
+ parsed = json.loads(stripped)
413
+ if isinstance(parsed, dict) and "data" in parsed:
414
+ return str(parsed["data"])
415
+ except Exception:
416
+ pass
417
+ return raw
418
+
419
+
420
+ def collect_stream_window(
421
+ stream_iter: Any,
422
+ wait_sec: float = 5.0,
423
+ idle_break_sec: float = 1.2,
424
+ ) -> tuple[str, bool]:
425
+ """Read from a potentially infinite SSE generator for at most `wait_sec` without hanging."""
426
+ q: queue.Queue[tuple[str, Any]] = queue.Queue()
427
+ stop_flag = threading.Event()
428
+
429
+ def _reader() -> None:
430
+ try:
431
+ for item in stream_iter:
432
+ if stop_flag.is_set():
433
+ break
434
+ q.put(("item", item))
435
+ q.put(("eof", None))
436
+ except Exception as exc:
437
+ q.put(("err", exc))
438
+
439
+ t = threading.Thread(target=_reader, daemon=True)
440
+ t.start()
441
+
442
+ chunks: list[str] = []
443
+ reached_eof = False
444
+ deadline = time.monotonic() + max(0.5, float(wait_sec))
445
+
446
+ try:
447
+ while True:
448
+ rem = deadline - time.monotonic()
449
+ if rem <= 0:
450
+ break
451
+ timeout = min(rem, idle_break_sec if chunks else rem)
452
+ try:
453
+ kind, payload = q.get(timeout=max(0.05, timeout))
454
+ except queue.Empty:
455
+ if chunks:
456
+ break
457
+ continue
458
+
459
+ if kind == "eof":
460
+ reached_eof = True
461
+ break
462
+ if kind == "err":
463
+ if not chunks:
464
+ raise payload
465
+ break
466
+ chunks.append(_extract_event_text(payload))
467
+ finally:
468
+ stop_flag.set()
469
+ close_fn = getattr(stream_iter, "close", None)
470
+ if callable(close_fn):
471
+ try:
472
+ close_fn()
473
+ except Exception:
474
+ pass
475
+
476
+ return "".join(chunks), reached_eof
477
+
478
+
479
+ def read_batch_logs_windowed(
480
+ settings: Settings,
481
+ slot: str = "batch-1",
482
+ kernel_ref: str = "",
483
+ tail_lines: int = 100,
484
+ grep: str = "",
485
+ wait_sec: float = 5.0,
486
+ ) -> dict[str, Any]:
487
+ """Read live or persisted execution logs via Kaggle Host SSE even when enable_internet=false."""
488
+ api = get_kaggle_api(settings)
489
+ s = normalize_slot(slot)
490
+ sess = load_active_session(s)
491
+
492
+ if kernel_ref:
493
+ target_ref = kernel_ref.strip()
494
+ versioned_ref = target_ref
495
+ elif sess and sess.kernel_ref:
496
+ target_ref = sess.kernel_ref
497
+ versioned_ref = (
498
+ f"{sess.kernel_ref}/{sess.version_number}" if sess.version_number else sess.kernel_ref
499
+ )
500
+ else:
501
+ target_ref = settings.kernel_ref_for_slot(s, mode="batch")
502
+ versioned_ref = target_ref
503
+
504
+ kinfo = get_kernel_status(api, versioned_ref)
505
+ raw_log = ""
506
+ stream_eof = False
507
+ note = ""
508
+
509
+ if kinfo["status"] not in {"NOT_CREATED_YET"}:
510
+ try:
511
+ with protect_stdout():
512
+ gen = api.kernels_logs_stream(versioned_ref)
513
+ raw_log, stream_eof = collect_stream_window(gen, wait_sec=wait_sec)
514
+ except Exception as exc:
515
+ note = f"stream_fallback ({exc})"
516
+
517
+ if not raw_log and kinfo["status"] in TERMINAL_KERNEL_STATUSES:
518
+ try:
519
+ with protect_stdout():
520
+ raw_log = api.kernels_logs(versioned_ref) or ""
521
+ except Exception as exc:
522
+ note = f"logs_error ({exc})"
523
+
524
+ # Cache cumulative snapshots locally per slot/version so SSE deltas aren't lost across calls
525
+ cache_dir = STATE_DIR / "batch_logs"
526
+ cache_dir.mkdir(parents=True, exist_ok=True)
527
+ safe_name = re.sub(r"[^a-zA-Z0-9_.-]+", "_", versioned_ref)
528
+ cache_file = cache_dir / f"{safe_name}.log"
529
+
530
+ if raw_log:
531
+ if stream_eof or kinfo["status"] in TERMINAL_KERNEL_STATUSES:
532
+ cache_file.write_text(raw_log, encoding="utf-8")
533
+ else:
534
+ existing_txt = cache_file.read_text(encoding="utf-8") if cache_file.is_file() else ""
535
+ if raw_log not in existing_txt:
536
+ cache_file.write_text(existing_txt + raw_log, encoding="utf-8")
537
+
538
+ full_text = cache_file.read_text(encoding="utf-8") if cache_file.is_file() else raw_log
539
+ cleaned = clean_log_text(full_text)
540
+ lines = cleaned.splitlines()
541
+ if grep:
542
+ pat = re.compile(grep, re.IGNORECASE)
543
+ lines = [ln for ln in lines if pat.search(ln)]
544
+ tail = lines[-max(1, int(tail_lines)) :]
545
+
546
+ return {
547
+ "slot": s,
548
+ "kernel_ref": versioned_ref,
549
+ "kaggle_api_status": kinfo["status"],
550
+ "failure_message": kinfo["failure_message"],
551
+ "returned_lines": len(tail),
552
+ "logs": "\n".join(tail),
553
+ **({"note": note} if note else {}),
554
+ }