evalstate HF Staff commited on
Commit
50009f2
·
verified ·
1 Parent(s): c135b0e

Fall back to complete downloads for stalled shards

Browse files

Read each source shard atomically. If HfFileSystem streaming exhausts retries with a read timeout, download the complete pinned blob and process it instead of failing the daily publisher. Apply the same path to session ingestion and dashboard query scans.

Files changed (2) hide show
  1. pipeline.py +87 -59
  2. test_pipeline.py +33 -3
pipeline.py CHANGED
@@ -12,7 +12,6 @@ from __future__ import annotations
12
 
13
  import argparse
14
  import json
15
- import os
16
  import re
17
  import sys
18
  import tempfile
@@ -21,10 +20,6 @@ from datetime import date, datetime, timedelta, timezone
21
  from pathlib import Path
22
  from typing import Any, Iterable
23
 
24
- # Large source scans occasionally stall longer than the Hub client's 10-second
25
- # default while reading an otherwise healthy shard.
26
- os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "60"
27
-
28
  from huggingface_hub import CommitOperationAdd, HfApi, HfFileSystem, hf_hub_download
29
  from huggingface_hub.errors import EntryNotFoundError
30
 
@@ -306,19 +301,47 @@ def source_paths(fs: HfFileSystem, repo: str, revision: str, days: Iterable[date
306
  return found
307
 
308
 
309
- def read_events(fs: HfFileSystem, paths: Iterable[str], counters: dict[str, int]) -> Iterable[dict[str, Any]]:
310
- for path in paths:
 
 
 
 
 
 
311
  with fs.open(path, "rt") as stream:
312
- for line in stream:
313
- counters["source_rows"] += 1
314
- try:
315
- event = json.loads(line)
316
- except json.JSONDecodeError:
317
- counters["invalid_json"] += 1
318
- continue
319
- if event.get("methodName") == "initialize":
320
- counters["initialize_rows"] += 1
321
- yield event
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
 
323
 
324
  def client_group(name: str) -> str | None:
@@ -443,47 +466,46 @@ def dashboard_report(
443
  paths = report_paths(fs, repo, revision, start, through)
444
 
445
  for path in paths:
446
- with fs.open(path, "rt") as stream:
447
- for line in stream:
448
- try:
449
- row = json.loads(line)
450
- seen = parse_time(row["time"])
451
- except (json.JSONDecodeError, KeyError, TypeError, ValueError):
452
- health["invalid_query_rows"] += 1
453
- continue
454
- if not start <= seen.date() <= through or row.get("methodName") in {"initialize", "session_delete"}:
455
- continue
456
- name = row.get("name")
457
- if not isinstance(name, str) or not name:
458
- health["missing_client_name_tool_calls"] += 1
459
- continue
460
- if "mcp-remote" in name.casefold():
461
- health["excluded_mcp_remote_tool_calls"] += 1
462
- continue
463
- protocol = row.get("protocolVersion")
464
- if not isinstance(protocol, str) or not protocol:
465
- health["missing_protocol_version_tool_calls"] += 1
466
- continue
467
- if protocol not in VALID_PROTOCOLS:
468
- health["invalid_protocol_version_tool_calls"] += 1
469
- continue
470
-
471
- stamp = seen.date().isoformat()
472
- health["valid_tool_calls"] += 1
473
- group = client_group(name)
474
- if group:
475
- named_daily[group][stamp][protocol] += 1
476
- group_names[group].add(name)
477
- if protocol == MODERN_PROTOCOL:
478
- capability_counts[group]["observations"] += 1
479
- flags, valid = feature_flags(row.get("clientCapabilities"))
480
- health["modern_tool_calls_with_valid_capabilities" if valid else "modern_tool_calls_without_valid_capabilities"] += 1
481
- if valid and flags:
482
- for feature, present in flags.items():
483
- capability_counts[group][feature] += present
484
- else:
485
- other_daily[name][stamp][protocol] += 1
486
- other_totals[name] += 1
487
 
488
  dates = [day.isoformat() for day in daterange(start, through)]
489
  coverage = {}
@@ -598,7 +620,13 @@ def run(args: argparse.Namespace) -> int:
598
  fs = HfFileSystem()
599
  partitions = source_paths(fs, args.source_repo, source.sha, daterange(start, through))
600
  counters: dict[str, int] = defaultdict(int)
601
- events = read_events(fs, (path for paths in partitions.values() for path in paths), counters)
 
 
 
 
 
 
602
  state, updates = merge(rows, events)
603
  raw, dedup = sorted_raw(state), deduplicate(state.values())
604
  report = dashboard_report(
 
12
 
13
  import argparse
14
  import json
 
15
  import re
16
  import sys
17
  import tempfile
 
20
  from pathlib import Path
21
  from typing import Any, Iterable
22
 
 
 
 
 
23
  from huggingface_hub import CommitOperationAdd, HfApi, HfFileSystem, hf_hub_download
24
  from huggingface_hub.errors import EntryNotFoundError
25
 
 
301
  return found
302
 
303
 
304
+ def source_lines(
305
+ fs: HfFileSystem,
306
+ path: str,
307
+ repo: str,
308
+ revision: str,
309
+ download=hf_hub_download,
310
+ ) -> list[str]:
311
+ try:
312
  with fs.open(path, "rt") as stream:
313
+ text = stream.read()
314
+ except Exception as error:
315
+ if "timed out" not in str(error).casefold():
316
+ raise
317
+ prefix = f"datasets/{repo}@{revision}/"
318
+ if not path.startswith(prefix):
319
+ raise RuntimeError(f"cannot resolve timed-out source path: {path}") from error
320
+ filename = path.removeprefix(prefix)
321
+ print(f"stream timed out; downloading complete source shard: {filename}", file=sys.stderr)
322
+ cached = download(repo_id=repo, filename=filename, repo_type="dataset", revision=revision)
323
+ text = Path(cached).read_text()
324
+ return text.splitlines()
325
+
326
+
327
+ def read_events(
328
+ fs: HfFileSystem,
329
+ paths: Iterable[str],
330
+ counters: dict[str, int],
331
+ repo: str,
332
+ revision: str,
333
+ ) -> Iterable[dict[str, Any]]:
334
+ for path in paths:
335
+ for line in source_lines(fs, path, repo, revision):
336
+ counters["source_rows"] += 1
337
+ try:
338
+ event = json.loads(line)
339
+ except json.JSONDecodeError:
340
+ counters["invalid_json"] += 1
341
+ continue
342
+ if event.get("methodName") == "initialize":
343
+ counters["initialize_rows"] += 1
344
+ yield event
345
 
346
 
347
  def client_group(name: str) -> str | None:
 
466
  paths = report_paths(fs, repo, revision, start, through)
467
 
468
  for path in paths:
469
+ for line in source_lines(fs, path, repo, revision):
470
+ try:
471
+ row = json.loads(line)
472
+ seen = parse_time(row["time"])
473
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):
474
+ health["invalid_query_rows"] += 1
475
+ continue
476
+ if not start <= seen.date() <= through or row.get("methodName") in {"initialize", "session_delete"}:
477
+ continue
478
+ name = row.get("name")
479
+ if not isinstance(name, str) or not name:
480
+ health["missing_client_name_tool_calls"] += 1
481
+ continue
482
+ if "mcp-remote" in name.casefold():
483
+ health["excluded_mcp_remote_tool_calls"] += 1
484
+ continue
485
+ protocol = row.get("protocolVersion")
486
+ if not isinstance(protocol, str) or not protocol:
487
+ health["missing_protocol_version_tool_calls"] += 1
488
+ continue
489
+ if protocol not in VALID_PROTOCOLS:
490
+ health["invalid_protocol_version_tool_calls"] += 1
491
+ continue
492
+
493
+ stamp = seen.date().isoformat()
494
+ health["valid_tool_calls"] += 1
495
+ group = client_group(name)
496
+ if group:
497
+ named_daily[group][stamp][protocol] += 1
498
+ group_names[group].add(name)
499
+ if protocol == MODERN_PROTOCOL:
500
+ capability_counts[group]["observations"] += 1
501
+ flags, valid = feature_flags(row.get("clientCapabilities"))
502
+ health["modern_tool_calls_with_valid_capabilities" if valid else "modern_tool_calls_without_valid_capabilities"] += 1
503
+ if valid and flags:
504
+ for feature, present in flags.items():
505
+ capability_counts[group][feature] += present
506
+ else:
507
+ other_daily[name][stamp][protocol] += 1
508
+ other_totals[name] += 1
 
509
 
510
  dates = [day.isoformat() for day in daterange(start, through)]
511
  coverage = {}
 
620
  fs = HfFileSystem()
621
  partitions = source_paths(fs, args.source_repo, source.sha, daterange(start, through))
622
  counters: dict[str, int] = defaultdict(int)
623
+ events = read_events(
624
+ fs,
625
+ (path for paths in partitions.values() for path in paths),
626
+ counters,
627
+ args.source_repo,
628
+ source.sha,
629
+ )
630
  state, updates = merge(rows, events)
631
  raw, dedup = sorted_raw(state), deduplicate(state.values())
632
  report = dashboard_report(
test_pipeline.py CHANGED
@@ -23,10 +23,40 @@ class SourceSimulator:
23
 
24
 
25
  class PipelineTest(unittest.TestCase):
26
- def test_hub_download_timeout_allows_slow_shards(self):
27
- from huggingface_hub.constants import HF_HUB_DOWNLOAD_TIMEOUT
 
 
28
 
29
- self.assertEqual(HF_HUB_DOWNLOAD_TIMEOUT, 60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  def test_merge_retains_seed_and_latest_event(self):
32
  seed = [{"name": "Cursor", "version": "1", "capabilities": "{}", "last_seen": "2026-07-22T00:00:00Z"}]
 
23
 
24
 
25
  class PipelineTest(unittest.TestCase):
26
+ def test_source_lines_downloads_complete_shard_after_stream_timeout(self):
27
+ class TimedOutSource:
28
+ def open(self, path, mode):
29
+ raise TimeoutError("The read operation timed out")
30
 
31
+ with tempfile.TemporaryDirectory() as directory:
32
+ fallback = Path(directory) / "shard.jsonl"
33
+ fallback.write_text('{"methodName":"initialize"}\n{"methodName":"session_delete"}\n')
34
+ calls = []
35
+
36
+ def download(**kwargs):
37
+ calls.append(kwargs)
38
+ return fallback
39
+
40
+ lines = pipeline.source_lines(
41
+ TimedOutSource(),
42
+ "datasets/source/repo@revision/sessions/2026-08-29/shard.jsonl",
43
+ "source/repo",
44
+ "revision",
45
+ download,
46
+ )
47
+
48
+ self.assertEqual(lines, ['{"methodName":"initialize"}', '{"methodName":"session_delete"}'])
49
+ self.assertEqual(
50
+ calls,
51
+ [
52
+ {
53
+ "repo_id": "source/repo",
54
+ "filename": "sessions/2026-08-29/shard.jsonl",
55
+ "repo_type": "dataset",
56
+ "revision": "revision",
57
+ }
58
+ ],
59
+ )
60
 
61
  def test_merge_retains_seed_and_latest_event(self):
62
  seed = [{"name": "Cursor", "version": "1", "capabilities": "{}", "last_seen": "2026-07-22T00:00:00Z"}]