-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1789 lines (1449 loc) Β· 65.2 KB
/
Copy pathapp.py
File metadata and controls
1789 lines (1449 loc) Β· 65.2 KB
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gradio as gr
from gradio_leaderboard import Leaderboard, ColumnFilter
import json
import os
import time
import tempfile
import requests
from datetime import datetime, timezone, timedelta
from collections import defaultdict
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.errors import HfHubHTTPError
from dotenv import load_dotenv
import pandas as pd
import random
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from google.cloud import bigquery
import backoff
# Load environment variables
load_dotenv()
# =============================================================================
# CONFIGURATION
# =============================================================================
AGENTS_REPO = "SWE-Arena/bot_metadata" # HuggingFace dataset for agent metadata
ISSUE_METADATA_REPO = "SWE-Arena/issue_metadata" # HuggingFace dataset for issue metadata
LEADERBOARD_REPO = "SWE-Arena/leaderboard_metadata" # HuggingFace dataset for leaderboard metadata
LEADERBOARD_TIME_FRAME_DAYS = 180 # Time frame for leaderboard
UPDATE_TIME_FRAME_DAYS = 30 # How often to re-mine data via BigQuery
LEADERBOARD_COLUMNS = [
("Agent Name", "string"),
("Website", "string"),
("Total Issues", "number"),
("Resolved Issues", "number"),
("Resolved Rate (%)", "number"),
]
# =============================================================================
# HUGGINGFACE API WRAPPERS WITH BACKOFF
# =============================================================================
def is_rate_limit_error(e):
"""Check if the exception is a rate limit error (429)."""
return isinstance(e, HfHubHTTPError) and e.response.status_code == 429
@backoff.on_exception(
backoff.expo,
HfHubHTTPError,
giveup=lambda e: not is_rate_limit_error(e),
max_tries=8,
base=300,
max_value=3600,
jitter=backoff.full_jitter,
on_backoff=lambda details: print(f" β³ Rate limited. Retrying in {details['wait']/60:.1f} minutes ({details['wait']:.0f}s) - attempt {details['tries']}/{8}...")
)
def list_repo_files_with_backoff(api, **kwargs):
"""List repo files with exponential backoff on rate limit errors."""
return api.list_repo_files(**kwargs)
@backoff.on_exception(
backoff.expo,
HfHubHTTPError,
giveup=lambda e: not is_rate_limit_error(e),
max_tries=8,
base=300,
max_value=3600,
jitter=backoff.full_jitter,
on_backoff=lambda details: print(f" β³ Rate limited. Retrying in {details['wait']/60:.1f} minutes ({details['wait']:.0f}s) - attempt {details['tries']}/{8}...")
)
def hf_hub_download_with_backoff(**kwargs):
"""Download from HF Hub with exponential backoff on rate limit errors."""
return hf_hub_download(**kwargs)
@backoff.on_exception(
backoff.expo,
HfHubHTTPError,
giveup=lambda e: not is_rate_limit_error(e),
max_tries=8,
base=300,
max_value=3600,
jitter=backoff.full_jitter,
on_backoff=lambda details: print(f" β³ Rate limited. Retrying in {details['wait']/60:.1f} minutes ({details['wait']:.0f}s) - attempt {details['tries']}/{8}...")
)
def upload_file_with_backoff(api, **kwargs):
"""Upload file with exponential backoff on rate limit errors."""
return api.upload_file(**kwargs)
@backoff.on_exception(
backoff.expo,
HfHubHTTPError,
giveup=lambda e: not is_rate_limit_error(e),
max_tries=8,
base=300,
max_value=3600,
jitter=backoff.full_jitter,
on_backoff=lambda details: print(f" β³ Rate limited. Retrying in {details['wait']/60:.1f} minutes ({details['wait']:.0f}s) - attempt {details['tries']}/{8}...")
)
def upload_folder_with_backoff(api, **kwargs):
"""Upload folder with exponential backoff on rate limit errors."""
return api.upload_folder(**kwargs)
# =============================================================================
# JSONL FILE OPERATIONS
# =============================================================================
def load_jsonl(filename):
"""Load JSONL file and return list of dictionaries."""
if not os.path.exists(filename):
return []
data = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line:
try:
entry = json.loads(line)
data.append(entry)
except json.JSONDecodeError as e:
print(f"Warning: Skipping invalid JSON line: {e}")
return data
def save_jsonl(filename, data):
"""Save list of dictionaries to JSONL file."""
with open(filename, 'w', encoding='utf-8') as f:
for item in data:
f.write(json.dumps(item) + '\n')
def cache_to_dict(cache_list):
"""Convert list of cache entries to dictionary by identifier."""
return {entry['github_identifier']: entry for entry in cache_list}
def dict_to_cache(cache_dict):
"""Convert dictionary back to list of values."""
return list(cache_dict.values())
def normalize_date_format(date_string):
"""
Convert date strings to standardized ISO 8601 format with Z suffix.
Handles both old format (2025-10-15T23:23:47.983068) and new format (2025-10-15T23:23:47Z).
Also handles space separator (2025-06-23 07:18:28) and incomplete timezone offsets (+00).
"""
if not date_string or date_string == 'N/A':
return 'N/A'
try:
# Replace space with 'T' for ISO format compatibility
date_string = date_string.replace(' ', 'T')
# Fix incomplete timezone offset (+00 or -00 -> +00:00 or -00:00)
if date_string[-3:-2] in ('+', '-') and ':' not in date_string[-3:]:
date_string = date_string + ':00'
# Parse the date string (handles both with and without microseconds)
dt = datetime.fromisoformat(date_string.replace('Z', '+00:00'))
# Convert to standardized format
return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
except Exception as e:
print(f"Warning: Could not parse date '{date_string}': {e}")
return date_string
# =============================================================================
# BIGQUERY OPERATIONS
# =============================================================================
def get_bigquery_client():
"""
Initialize BigQuery client using credentials from environment variable.
Expects GOOGLE_APPLICATION_CREDENTIALS_JSON environment variable containing
the service account JSON credentials as a string.
"""
# Get the JSON content from environment variable
creds_json = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS_JSON')
if creds_json:
# Create a temporary file to store credentials
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_file:
temp_file.write(creds_json)
temp_path = temp_file.name
# Set environment variable to point to temp file
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = temp_path
# Initialize BigQuery client
client = bigquery.Client()
# Clean up temp file
os.unlink(temp_path)
return client
else:
raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")
def generate_table_union_statements(start_date, end_date):
"""
Generate UNION ALL statements for githubarchive.month tables in date range.
Args:
start_date: Start datetime
end_date: End datetime
Returns:
String with UNION ALL SELECT statements for all monthly tables in range
"""
table_names = []
# Start from the beginning of start_date's month
current_date = start_date.replace(day=1)
end_month = end_date.replace(day=1)
while current_date <= end_month:
table_name = f"`githubarchive.month.{current_date.strftime('%Y%m')}`"
table_names.append(table_name)
# Move to next month
if current_date.month == 12:
current_date = current_date.replace(year=current_date.year + 1, month=1)
else:
current_date = current_date.replace(month=current_date.month + 1)
# Create UNION ALL chain
union_parts = [f"SELECT * FROM {table}" for table in table_names]
return " UNION ALL ".join(union_parts)
def fetch_issue_metadata_batched(client, identifiers, start_date, end_date, batch_size=100, upload_immediately=True):
"""
Fetch issue metadata for ALL agents using BATCHED BigQuery queries.
Splits agents into smaller batches to avoid performance issues with large UNNEST arrays
and correlated subqueries. Each batch query runs much faster than one massive query.
Args:
client: BigQuery client instance
identifiers: List of GitHub usernames/bot identifiers
start_date: Start datetime (timezone-aware)
end_date: End datetime (timezone-aware)
batch_size: Number of agents per batch (default: 100)
upload_immediately: Upload results to HuggingFace immediately after each batch (default: True)
Returns:
Dictionary mapping agent identifier to list of issue metadata
"""
print(f"\nπ Querying BigQuery for {len(identifiers)} agents using BATCHED approach")
print(f" Batch size: {batch_size} agents per query")
print(f" Upload mode: {'Immediate (after each batch)' if upload_immediately else 'Deferred (after all batches)'}")
# Split identifiers into batches
batches = [identifiers[i:i + batch_size] for i in range(0, len(identifiers), batch_size)]
print(f" Total batches: {len(batches)}")
# Collect results from all batches
all_metadata = {}
for batch_num, batch_identifiers in enumerate(batches, 1):
print(f"\n{'β'*80}")
print(f"π¦ Processing Batch {batch_num}/{len(batches)} ({len(batch_identifiers)} agents)")
print(f"{'β'*80}")
try:
batch_results = fetch_all_issue_metadata_single_query(
client, batch_identifiers, start_date, end_date
)
# Merge results
for identifier, metadata_list in batch_results.items():
if identifier in all_metadata:
all_metadata[identifier].extend(metadata_list)
else:
all_metadata[identifier] = metadata_list
print(f" β Batch {batch_num} completed: {len(batch_results)} agents with data")
# Upload immediately after this batch if enabled
if upload_immediately and batch_results:
print(f"\n π€ Uploading batch {batch_num}/{len(batches)} results to HuggingFace...")
upload_success = 0
upload_errors = 0
for identifier, metadata_list in batch_results.items():
if metadata_list:
if save_issue_metadata_to_hf(metadata_list, identifier):
upload_success += 1
else:
upload_errors += 1
print(f" β Batch {batch_num}/{len(batches)} upload complete ({upload_success} agents uploaded, {upload_errors} errors)")
except Exception as e:
print(f" β Batch {batch_num} failed: {str(e)}")
print(f" Continuing with remaining batches...")
import traceback
traceback.print_exc()
continue
print(f"\n{'='*80}")
print(f"β
All batches completed!")
print(f" Total agents with data: {len(all_metadata)}")
total_issues = sum(len(issues) for issues in all_metadata.values())
print(f" Total issues found: {total_issues}")
print(f"{'='*80}\n")
return all_metadata
def fetch_all_issue_metadata_single_query(client, identifiers, start_date, end_date):
"""
Fetch issue metadata for a batch of agents using ONE comprehensive BigQuery query.
This query fetches IssuesEvent and IssueCommentEvent from GitHub Archive and
deduplicates to get the latest state of each issue. Filters by issue author,
commenter, or assignee.
NOTE: This function is designed for smaller batches (~100 agents). For large
numbers of agents, use fetch_issue_metadata_batched() instead.
Args:
client: BigQuery client instance
identifiers: List of GitHub usernames/bot identifiers (recommended: <100)
start_date: Start datetime (timezone-aware)
end_date: End datetime (timezone-aware)
Returns:
Dictionary mapping agent identifier to list of issue metadata:
{
'agent-identifier': [
{
'url': Issue URL,
'created_at': Issue creation timestamp,
'closed_at': Close timestamp (if closed, else None),
'state_reason': Reason for closure (completed/not_planned/etc.)
},
...
],
...
}
"""
print(f"\nπ Querying BigQuery for {len(identifiers)} agents in SINGLE QUERY")
print(f" Time range: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")
# Generate table UNION statements for issue events
issue_tables = generate_table_union_statements(start_date, end_date)
# Build identifier list for IN clause (handle both bot and non-bot versions)
identifier_set = set()
for id in identifiers:
identifier_set.add(id)
# Also add stripped version without [bot] suffix
stripped = id.replace('[bot]', '')
if stripped != id:
identifier_set.add(stripped)
# Create array format for UNNEST (avoids 256KB query size limit)
identifier_array = '[' + ', '.join([f'"{id}"' for id in identifier_set]) + ']'
print(f" Total identifiers (including bot/non-bot variants): {len(identifier_set)}")
# Build comprehensive query with CTEs
query = f"""
WITH agent_identifiers AS (
-- Create a table of all agent identifiers using UNNEST
-- This avoids hitting BigQuery's 256KB query size limit with large IN clauses
SELECT identifier
FROM UNNEST({identifier_array}) AS identifier
),
issue_events AS (
-- Get all issue events and comment events for ALL agents
SELECT
JSON_EXTRACT_SCALAR(payload, '$.issue.html_url') as url,
JSON_EXTRACT_SCALAR(payload, '$.issue.created_at') as created_at,
JSON_EXTRACT_SCALAR(payload, '$.issue.closed_at') as closed_at,
JSON_EXTRACT_SCALAR(payload, '$.issue.state_reason') as state_reason,
JSON_EXTRACT_SCALAR(payload, '$.issue.user.login') as author,
JSON_EXTRACT_SCALAR(payload, '$.issue.assignee.login') as assignee,
JSON_EXTRACT_SCALAR(payload, '$.comment.user.login') as commenter,
JSON_EXTRACT_SCALAR(payload, '$.issue.number') as issue_number,
repo.name as repo_name,
created_at as event_time
FROM (
{issue_tables}
)
WHERE
type IN ('IssuesEvent', 'IssueCommentEvent')
-- Exclude pull requests (they have pull_request field)
AND JSON_EXTRACT(payload, '$.issue.pull_request') IS NULL
AND JSON_EXTRACT_SCALAR(payload, '$.issue.html_url') IS NOT NULL
-- Filter by author OR commenter OR assignee
AND (
JSON_EXTRACT_SCALAR(payload, '$.issue.user.login') IN (SELECT identifier FROM agent_identifiers)
OR JSON_EXTRACT_SCALAR(payload, '$.comment.user.login') IN (SELECT identifier FROM agent_identifiers)
OR JSON_EXTRACT_SCALAR(payload, '$.issue.assignee.login') IN (SELECT identifier FROM agent_identifiers)
)
),
latest_states AS (
-- Deduplicate to get latest state for each issue
SELECT
url,
created_at,
closed_at,
state_reason,
author,
assignee,
commenter
FROM issue_events
QUALIFY ROW_NUMBER() OVER (
PARTITION BY repo_name, issue_number
ORDER BY event_time DESC
) = 1
),
agent_issues AS (
-- Map each issue to its relevant agent(s)
SELECT DISTINCT
CASE
WHEN author IN (SELECT identifier FROM agent_identifiers) THEN author
WHEN commenter IN (SELECT identifier FROM agent_identifiers) THEN commenter
WHEN assignee IN (SELECT identifier FROM agent_identifiers) THEN assignee
ELSE NULL
END as agent_identifier,
url,
created_at,
closed_at,
state_reason
FROM latest_states
WHERE
author IN (SELECT identifier FROM agent_identifiers)
OR commenter IN (SELECT identifier FROM agent_identifiers)
OR assignee IN (SELECT identifier FROM agent_identifiers)
)
SELECT
agent_identifier,
url,
created_at,
closed_at,
state_reason
FROM agent_issues
WHERE agent_identifier IS NOT NULL
ORDER BY agent_identifier, created_at DESC
"""
# Calculate number of days for reporting
query_days = (end_date - start_date).days
print(f" Querying {query_days} days for issue and comment events...")
print(f" Agents: {', '.join(identifiers[:5])}{'...' if len(identifiers) > 5 else ''}")
try:
query_job = client.query(query)
results = list(query_job.result())
print(f" β Found {len(results)} total issue records across all agents")
# Group results by agent
metadata_by_agent = defaultdict(list)
for row in results:
agent_id = row.agent_identifier
# Convert datetime objects to ISO strings
created_at = row.created_at
if hasattr(created_at, 'isoformat'):
created_at = created_at.isoformat()
closed_at = row.closed_at
if hasattr(closed_at, 'isoformat'):
closed_at = closed_at.isoformat()
metadata_by_agent[agent_id].append({
'url': row.url,
'created_at': created_at,
'closed_at': closed_at,
'state_reason': row.state_reason,
})
# Print breakdown by agent
print(f"\n π Results breakdown by agent:")
for identifier in identifiers:
# Check both original and stripped versions
count = len(metadata_by_agent.get(identifier, []))
stripped = identifier.replace('[bot]', '')
if stripped != identifier:
count += len(metadata_by_agent.get(stripped, []))
if count > 0:
# Merge both versions if needed
all_metadata = metadata_by_agent.get(identifier, []) + metadata_by_agent.get(stripped, [])
completed_count = sum(1 for m in all_metadata if m['state_reason'] == 'completed')
closed_count = sum(1 for m in all_metadata if m['closed_at'] is not None)
open_count = count - closed_count
print(f" {identifier}: {count} issues ({completed_count} completed, {closed_count} closed, {open_count} open)")
# Convert defaultdict to regular dict and merge bot/non-bot versions
final_metadata = {}
for identifier in identifiers:
combined = metadata_by_agent.get(identifier, [])
stripped = identifier.replace('[bot]', '')
if stripped != identifier and stripped in metadata_by_agent:
combined.extend(metadata_by_agent[stripped])
if combined:
final_metadata[identifier] = combined
return final_metadata
except Exception as e:
print(f" β BigQuery error: {str(e)}")
import traceback
traceback.print_exc()
return {}
# =============================================================================
# GITHUB API OPERATIONS (Minimal - for validation only)
# =============================================================================
def get_github_token():
"""Get GitHub token from environment variables for validation purposes."""
token = os.getenv('GITHUB_TOKEN')
if not token:
print("Warning: GITHUB_TOKEN not found for validation")
return token
def validate_github_username(identifier):
"""Verify that a GitHub identifier exists (simple validation for submission)."""
try:
token = get_github_token()
headers = {'Authorization': f'token {token}'} if token else {}
url = f'https://api.github.com/users/{identifier}'
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
return True, "Username is valid"
elif response.status_code == 404:
return False, "GitHub identifier not found"
else:
return False, f"Validation error: HTTP {response.status_code}"
except Exception as e:
return False, f"Validation error: {str(e)}"
# =============================================================================
# ISSUE METADATA OPERATIONS
# =============================================================================
def extract_issue_metadata(issue):
"""
Extract minimal issue metadata for efficient storage.
Only keeps essential fields: url, created_at, closed_at, state_reason.
Note: agent_name is not stored as it's inferred from the folder structure.
Issue states:
- state: "open" or "closed"
- state_reason: "completed" (resolved), "not_planned" (closed as not planned), or None (still open)
"""
# Extract dates and state
created_at = issue.get('created_at')
closed_at = issue.get('closed_at')
state = issue.get('state')
state_reason = issue.get('state_reason')
return {
'url': issue.get('url'),
'created_at': created_at,
'closed_at': closed_at,
'state': state,
'state_reason': state_reason
}
def calculate_issue_stats_from_metadata(metadata_list):
"""
Calculate statistics from a list of issue metadata (lightweight objects).
Works with minimal metadata: url, created_at, closed_at, state, state_reason.
Returns a dictionary with comprehensive issue metrics.
Resolved Rate is calculated as:
completed issues / closed issues * 100
Completed Issues = issues closed as completed (state_reason="completed")
Closed Issues = all issues that have been closed (closed_at is not None)
We do NOT count issues closed as not planned (state_reason="not_planned") as resolved,
but they ARE counted in the denominator as closed issues.
"""
total_issues = len(metadata_list)
# Count closed issues (those with closed_at timestamp)
closed_issues = sum(1 for issue_meta in metadata_list
if issue_meta.get('closed_at') is not None)
# Count completed issues (subset of closed issues with state_reason="completed")
completed = sum(1 for issue_meta in metadata_list
if issue_meta.get('state_reason') == 'completed')
# Calculate resolved rate as: completed / closed (not completed / total)
resolved_rate = (completed / closed_issues * 100) if closed_issues > 0 else 0
return {
'total_issues': total_issues,
'closed_issues': closed_issues,
'resolved_issues': completed,
'resolved_rate': round(resolved_rate, 2),
}
def calculate_monthly_metrics_by_agent(top_n=None):
"""
Calculate monthly metrics for all agents (or top N agents) for visualization.
Loads data directly from SWE-Arena/issue_metadata dataset.
Args:
top_n: If specified, only return metrics for the top N agents by total issues.
Agents are ranked by their total issue count across all months.
Returns:
dict: {
'agents': list of agent names,
'months': list of month labels (e.g., '2025-01'),
'data': {
agent_name: {
'resolved_rates': list of resolved rates by month,
'total_issues': list of issue counts by month,
'resolved_issues': list of resolved issue counts by month
}
}
}
"""
# Load ALL agents from HuggingFace agents repo
agents = load_agents_from_hf()
# Create mapping from agent_identifier to agent_name
identifier_to_name = {agent.get('github_identifier'): agent.get('name') for agent in agents if agent.get('github_identifier')}
# Load all issue metadata from issue_metadata dataset
all_metadata = load_issue_metadata()
if not all_metadata:
return {'agents': [], 'months': [], 'data': {}}
# Group by agent and month
agent_month_data = defaultdict(lambda: defaultdict(list))
for issue_meta in all_metadata:
agent_identifier = issue_meta.get('agent_identifier')
created_at = issue_meta.get('created_at')
if not agent_identifier or not created_at:
continue
# Get agent_name from identifier
agent_name = identifier_to_name.get(agent_identifier, agent_identifier)
try:
dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
month_key = f"{dt.year}-{dt.month:02d}"
agent_month_data[agent_name][month_key].append(issue_meta)
except Exception as e:
print(f"Warning: Could not parse date '{created_at}': {e}")
continue
# Get all unique months and sort them
all_months = set()
for agent_data in agent_month_data.values():
all_months.update(agent_data.keys())
months = sorted(list(all_months))
# Calculate metrics for each agent and month
result_data = {}
for agent_name, month_dict in agent_month_data.items():
resolved_rates = []
total_issues_list = []
resolved_issues_list = []
for month in months:
issues_in_month = month_dict.get(month, [])
# Count completed issues (those with state_reason="completed")
completed_count = sum(1 for issue in issues_in_month if issue.get('state_reason') == 'completed')
# Count closed issues (those with closed_at timestamp)
closed_count = sum(1 for issue in issues_in_month if issue.get('closed_at') is not None)
# Total issues created in this month
total_count = len(issues_in_month)
# Calculate resolved rate as: completed / closed (not completed / total)
resolved_rate = (completed_count / closed_count * 100) if closed_count > 0 else None
resolved_rates.append(resolved_rate)
total_issues_list.append(total_count)
resolved_issues_list.append(completed_count)
result_data[agent_name] = {
'resolved_rates': resolved_rates,
'total_issues': total_issues_list,
'resolved_issues': resolved_issues_list
}
# Filter to top N agents if specified
agents_list = sorted(list(agent_month_data.keys()))
if top_n is not None and top_n > 0:
# Calculate total issues for each agent across all months
agent_totals = []
for agent_name in agents_list:
total_issues = sum(result_data[agent_name]['total_issues'])
agent_totals.append((agent_name, total_issues))
# Sort by total issues (descending) and take top N
agent_totals.sort(key=lambda x: x[1], reverse=True)
top_agents = [agent_name for agent_name, _ in agent_totals[:top_n]]
# Filter result_data to only include top agents
result_data = {agent: result_data[agent] for agent in top_agents if agent in result_data}
agents_list = top_agents
return {
'agents': agents_list,
'months': months,
'data': result_data
}
# =============================================================================
# ISSUE METADATA STORAGE & RETRIEVAL
# =============================================================================
def group_metadata_by_date(metadata_list):
"""
Group issue metadata by exact date (year.month.day) for efficient daily storage.
Returns dict: {(year, month, day): [metadata_list]}
"""
grouped = defaultdict(list)
for issue_meta in metadata_list:
created_at = issue_meta.get('created_at')
if not created_at:
continue
try:
dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
key = (dt.year, dt.month, dt.day)
grouped[key].append(issue_meta)
except Exception as e:
print(f"Warning: Could not parse date '{created_at}': {e}")
return dict(grouped)
def save_issue_metadata_to_hf(metadata_list, agent_identifier):
"""
Save issue metadata to HuggingFace dataset, organized by [agent_identifier]/YYYY.MM.DD.jsonl.
Each file is stored in the agent's folder and named YYYY.MM.DD.jsonl for that day's issues.
This function uses COMPLETE OVERWRITE strategy (not append/deduplicate).
Uses upload_folder for single-commit batch uploads (avoids rate limit issues).
Args:
metadata_list: List of issue metadata dictionaries
agent_identifier: GitHub identifier of the agent (used as folder name)
"""
import tempfile
import shutil
temp_dir = None
try:
token = get_hf_token()
if not token:
raise Exception("No HuggingFace token found")
api = HfApi(token=token)
# Group by exact date (year, month, day)
grouped = group_metadata_by_date(metadata_list)
if not grouped:
print(f" No valid metadata to save for {agent_identifier}")
return False
# Create temporary directory for batch upload
temp_dir = tempfile.mkdtemp()
agent_folder = os.path.join(temp_dir, agent_identifier)
os.makedirs(agent_folder, exist_ok=True)
print(f"π¦ Preparing batch upload for {agent_identifier} ({len(grouped)} daily files)...")
# Process each daily file
for (issue_year, month, day), day_metadata in grouped.items():
filename = f"{agent_identifier}/{issue_year}.{month:02d}.{day:02d}.jsonl"
local_filename = os.path.join(agent_folder, f"{issue_year}.{month:02d}.{day:02d}.jsonl")
# Sort by created_at for better organization
day_metadata.sort(key=lambda x: x.get('created_at', ''), reverse=True)
# Save to temp directory (complete overwrite, no merging)
save_jsonl(local_filename, day_metadata)
print(f" Prepared {len(day_metadata)} issues for {filename}")
# Upload entire folder using upload_folder (single commit per agent)
print(f"π€ Uploading {len(grouped)} files ({len(metadata_list)} total issues)...")
upload_folder_with_backoff(
api,
folder_path=temp_dir,
repo_id=ISSUE_METADATA_REPO,
repo_type="dataset",
commit_message=f"Update issue metadata for {agent_identifier} - {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC"
)
print(f" β Batch upload complete for {agent_identifier}")
return True
except Exception as e:
print(f"β Error saving issue metadata: {str(e)}")
return False
finally:
# Always clean up temporary directory
if temp_dir and os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
def load_issue_metadata():
"""
Load issue metadata from the last LEADERBOARD_TIME_FRAME_DAYS only.
Structure: [agent_identifier]/YYYY.MM.DD.jsonl
Returns:
List of dictionaries with 'agent_identifier' added to each issue metadata.
Only includes issues within the last LEADERBOARD_TIME_FRAME_DAYS.
"""
# Calculate cutoff date based on LEADERBOARD_TIME_FRAME_DAYS
current_time = datetime.now(timezone.utc)
cutoff_date = current_time - timedelta(days=LEADERBOARD_TIME_FRAME_DAYS)
try:
api = HfApi()
token = get_hf_token()
# List all files in the repository
files = list_repo_files_with_backoff(api, repo_id=ISSUE_METADATA_REPO, repo_type="dataset")
# Filter for files within the time frame: [agent_identifier]/YYYY.MM.DD.jsonl
# Parse date from filename and only include files within LEADERBOARD_TIME_FRAME_DAYS
time_frame_files = []
for f in files:
if f.endswith('.jsonl'):
parts = f.split('/')
if len(parts) == 2: # [agent_identifier]/YYYY.MM.DD.jsonl
filename = parts[1]
try:
# Extract date from filename: YYYY.MM.DD.jsonl
date_part = filename.replace('.jsonl', '') # Get YYYY.MM.DD
date_components = date_part.split('.')
if len(date_components) == 3:
file_year, file_month, file_day = map(int, date_components)
file_date = datetime(file_year, file_month, file_day, tzinfo=timezone.utc)
# Only include files within the time frame
if file_date >= cutoff_date:
time_frame_files.append(f)
except Exception:
# Skip files with unparseable dates
continue
print(f"π₯ [LOAD] Reading cached issue metadata from HuggingFace ({len(time_frame_files)} files, last {LEADERBOARD_TIME_FRAME_DAYS} days)...")
all_metadata = []
for filename in time_frame_files:
try:
# Extract agent_identifier from path (first part)
# Format: agent_identifier/YYYY.MM.DD.jsonl
parts = filename.split('/')
if len(parts) != 2:
print(f" Warning: Unexpected filename format: {filename}")
continue
agent_identifier = parts[0]
file_path = hf_hub_download_with_backoff(
repo_id=ISSUE_METADATA_REPO,
filename=filename,
repo_type="dataset",
token=token
)
day_metadata = load_jsonl(file_path)
# Add agent_identifier and filter by date as a double-check
for issue_meta in day_metadata:
# Validate issue date against cutoff
created_at = issue_meta.get('created_at')
if created_at:
try:
dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
if dt < cutoff_date:
continue # Skip issues outside time frame
except Exception:
pass # Keep issues with unparseable dates
issue_meta['agent_identifier'] = agent_identifier
all_metadata.append(issue_meta)
print(f" β Loaded {len(day_metadata)} issues from {filename}")
except Exception as e:
print(f" Warning: Could not load {filename}: {str(e)}")
print(f"β Loaded {len(all_metadata)} total issues from last {LEADERBOARD_TIME_FRAME_DAYS} days")
return all_metadata
except Exception as e:
print(f"β Error loading issue metadata from last {LEADERBOARD_TIME_FRAME_DAYS} days: {str(e)}")
return []
def get_latest_issue_date_for_agent(agent_identifier):
"""
Get the latest issue creation date for an agent from stored metadata.
Used for incremental updates - only fetch issues newer than this date.
Structure: [agent_identifier]/YYYY.MM.DD.jsonl
Args:
agent_identifier: GitHub identifier of the agent
Returns:
datetime or None if no existing issues found.
"""
try:
api = HfApi()
token = get_hf_token()
# List all files in the repository
files = list_repo_files_with_backoff(api, repo_id=ISSUE_METADATA_REPO, repo_type="dataset")
# Filter for files in this agent's folder
# New structure: [agent_identifier]/YYYY.MM.DD.jsonl
agent_pattern = f"{agent_identifier}/"
agent_files = [f for f in files if f.startswith(agent_pattern) and f.endswith('.jsonl')]
if not agent_files:
return None
# Find latest created_at across all files
latest_date = None
for filename in agent_files:
try:
file_path = hf_hub_download_with_backoff(
repo_id=ISSUE_METADATA_REPO,
filename=filename,
repo_type="dataset",
token=token
)
metadata = load_jsonl(file_path)
for issue in metadata:
created_at = issue.get('created_at')
if created_at:
try:
dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
if latest_date is None or dt > latest_date:
latest_date = dt
except Exception:
continue
except Exception:
continue
return latest_date
except Exception:
return None
def get_daily_files_last_time_frame(agent_identifier):
"""
Get list of daily file paths for an agent from the configured time frame.
Args:
agent_identifier: GitHub identifier of the agent
Returns:
List of file paths in format: [agent_identifier]/YYYY.MM.DD.jsonl