Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
898 lines (774 loc) · 29.8 KB
/
Copy pathapp.py
File metadata and controls
898 lines (774 loc) · 29.8 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
from flask import Flask, request, jsonify
from flask_cors import CORS
from english_words import get_english_words_set
from random import sample
from datetime import datetime
from io import BytesIO
import uuid
import subprocess
import json
import zipfile
import os
import random
from urllib.parse import quote_plus
from pymongo import MongoClient
from dotenv import load_dotenv
import hashlib
import asyncio
import aiohttp
import time
import requests
from threading import Thread
from typing import Dict, Any, Optional
# 1) ADD gql imports
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
# 2) IMPORT nest_asyncio AND APPLY
import nest_asyncio
nest_asyncio.apply()
# ------------------ Shared Config Loader ------------------
"""
We will dynamically fetch the milestone config from your GitHub raw JSON,
convert it into a structure that your code can reference the same way
as the old MILESTONE_CONFIG.
"""
MILESTONE_CONFIG = {}
def load_milestones_config():
"""
Fetch the public milestones.json from GitHub and populate MILESTONE_CONFIG.
Example: https://raw.githubusercontent.com/ResilientApp/l-store-config/refs/heads/main/milestones.json
"""
url = "https://raw.githubusercontent.com/ResilientApp/l-store-config/refs/heads/main/milestones.json"
try:
r = requests.get(url)
r.raise_for_status()
data = r.json()
# Convert from array into old dictionary structure
tmp_config = {}
for m in data["milestones"]:
tmp_config[m["id"]] = {
"enabled": bool(m["enabled"]),
"extended_enabled": bool(m["extendedEnabled"])
}
return tmp_config
except Exception as e:
print("Error loading milestones config:", e)
return {}
# Attempt to load the config once at startup
MILESTONE_CONFIG = load_milestones_config()
# ----------------- Load environment variables -----------------
load_dotenv()
username = os.getenv('DB_USERNAME')
password = os.getenv('DB_PASSWORD')
host = os.getenv('DB_HOST')
port = os.getenv('DB_PORT')
db_name = os.getenv('DB_NAME')
deepseek_url = os.getenv('DEEPSEEK_URL')
deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')
resdb_url = os.getenv('RESILIENTDB_URL')
resdb_private_key = os.getenv('RESILIENTDB_PRIVATE_KEY')
resdb_public_key = os.getenv('RESILIENTDB_PUBLIC_KEY')
resdb_recipient_key = os.getenv('RESILIENTDB_RECIPIENT_KEY')
encoded_username = quote_plus(username)
encoded_password = quote_plus(password)
# Construct MongoDB URI
uri = f"mongodb+srv://{encoded_username}:{encoded_password}@{host}/{db_name}?retryWrites=true&w=majority"
client = MongoClient(uri)
db = client[db_name]
jobs_collection = db["jobs"]
app = Flask(__name__)
CORS(app)
BASE_DIR = os.path.expanduser('~/l-store-grader')
SUBMISSIONS_DIR = os.path.join(BASE_DIR, "submissions")
os.makedirs(SUBMISSIONS_DIR, exist_ok=True)
def generate_unique_name():
"""
Generates a random 3-word name: e.g. "Quiet Heart Lane"
"""
from english_words import get_english_words_set
words_list = list(get_english_words_set(['web2'], lower=True, alpha=True))
filtered_words_list = [w for w in words_list if len(w) <= 5]
chosen = random.sample(filtered_words_list, 3)
chosen = [word.capitalize() for word in chosen]
return " ".join(chosen)
def spawn_thread(target, *args, **kwargs) -> Thread:
t = Thread(target=target, args=args, kwargs=kwargs, daemon=True)
t.start()
return t
# ----------------- AI & Commit Extraction functions ------------------
async def read_python_files(folder_path):
code_data = ""
async def read_file(file_path, filename):
try:
content = await asyncio.to_thread(
lambda: open(file_path, 'r', encoding='utf-8', errors='replace').read()
)
return filename, content
except Exception as e:
print(f"Error reading {file_path}: {e}")
return filename, None
tasks = []
for root, _, files in os.walk(folder_path):
for file in files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
tasks.append(read_file(file_path, file))
results = await asyncio.gather(*tasks)
for filename, content in results:
if content:
code_data += f"\n# File: {filename}\n" + content + "\n"
return code_data
async def call_deepseek_api(prompt, model="deepseek-reasoner",
api_key=f"{deepseek_api_key}",
total_timeout=300):
"""
Calls the DeepSeek API with a configurable timeout (default=300 seconds).
"""
url = f"{deepseek_url}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": model,
"messages": [
{"role": "system", "content": "You are a code analysis assistant."},
{"role": "user", "content": prompt}
],
"stream": False
}
timeout = aiohttp.ClientTimeout(total=total_timeout)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
start_time = time.time()
async with session.post(url, headers=headers, json=payload) as response:
response.raise_for_status()
result = await response.json()
end_time = time.time()
result["request_time"] = round(end_time - start_time, 4)
return result
except aiohttp.ClientError as e:
return {"error": f"API call failed: {e}"}
def parse_response_content(response):
try:
content = response["choices"][0]["message"]["content"].strip()
if content.startswith("```"):
lines = content.splitlines()
lines = lines[1:] if len(lines) > 1 else lines
if lines and lines[-1].strip().startswith("```"):
lines = lines[:-1]
content = "\n".join(lines)
if not content.startswith("{"):
content = "{" + content
if not content.endswith("}"):
content = content + "}"
return json.loads(content)
except Exception as e:
print("Error parsing AI response:", e)
return {}
async def run_ai_tests(lstore_folder, ai_timeout=300):
"""
Runs multiple AI checks with a user-specified or default 300-second timeout.
"""
code_data = await read_python_files(lstore_folder)
prompt_ai = f"""
Analyze the code below and determine the likelihood it was generated by AI. Return a confidence score between 0 and 1.
Output only:
```json
"ai_generated_confidence": score
```
Here is the code:
```python
{code_data}
```
"""
prompt_pickle = f"""
Analyze the code below and check if the **pickle** module is used to serialize "tail" and "base" pages to disk. Return a higher confidence score if so.
Output only a JSON object with:
```json
"pickle_serialization_confidence": score
```
Here is the code:
```python
{code_data}
```
"""
prompt_struct = f"""
Analyze the code below and check if the **struct** module is used to serialize "tail" and "base" pages to disk. Return a higher confidence score if so.
Output only a JSON object with:
```json
"struct_serialization_confidence": score
```
Here is the code:
```python
{code_data}
```
"""
prompt_json_module = f"""
Analyze the code below and check if the **json** module is used to serialize "tail" and "base" pages to disk. Return a higher confidence score if so.
Output only a JSON object with:
```json
"json_serialization_confidence": score
```
Here is the code:
```python
{code_data}
```
"""
overall_start = time.time()
tasks = [
call_deepseek_api(prompt_ai, total_timeout=ai_timeout),
call_deepseek_api(prompt_pickle, total_timeout=ai_timeout),
call_deepseek_api(prompt_struct, total_timeout=ai_timeout),
call_deepseek_api(prompt_json_module, total_timeout=ai_timeout),
]
responses = await asyncio.gather(*tasks)
parsed_ai = parse_response_content(responses[0])
parsed_pickle = parse_response_content(responses[1])
parsed_struct = parse_response_content(responses[2])
parsed_json = parse_response_content(responses[3])
overall_end = time.time()
return {
"ai_generated_confidence": parsed_ai.get("ai_generated_confidence"),
"pickle_serialization_confidence": parsed_pickle.get("pickle_serialization_confidence"),
"struct_serialization_confidence": parsed_struct.get("struct_serialization_confidence"),
"json_serialization_confidence": parsed_json.get("json_serialization_confidence"),
"individual_request_times": {
"ai_generated": responses[0].get("request_time"),
"pickle": responses[1].get("request_time"),
"struct": responses[2].get("request_time"),
"json": responses[3].get("request_time"),
},
"total_time": round(overall_end - overall_start, 2)
}
def extract_commit_stats(folder_path):
stats = {
"local_git_commits": [],
"contributors": []
}
git_path = os.path.join(folder_path, ".git")
if os.path.exists(git_path):
try:
output = subprocess.check_output(
["git", "--no-pager", "log", "--pretty=format:%h - %an, %ad", "--date=short"],
cwd=folder_path
)
lines = output.decode("utf-8").splitlines()
stats["local_git_commits"] = lines
# Count commits per author
author_counts = {}
for line in lines:
parts = line.split('-', 1)
if len(parts) < 2:
continue
after_dash = parts[1].strip() # e.g. "Apratim Shukla, 2025-03-11"
comma_idx = after_dash.rfind(',')
if comma_idx != -1:
author_name = after_dash[:comma_idx].strip()
else:
author_name = after_dash
author_counts[author_name] = author_counts.get(author_name, 0) + 1
stats["contributors"] = [
{"name": name, "commits": count}
for name, count in author_counts.items()
]
except Exception as e:
stats["error"] = f"Error extracting git commit stats: {e}"
return stats
def merge_contributors(a, b):
""" Merge two arrays of {name, commits}, summing commits for duplicates. """
merged_map = {}
for obj in a:
merged_map[obj["name"]] = merged_map.get(obj["name"], 0) + obj["commits"]
for obj in b:
merged_map[obj["name"]] = merged_map.get(obj["name"], 0) + obj["commits"]
return [{"name": k, "commits": v} for k, v in merged_map.items()]
def milestone_tests(extract_path, lstore_path, milestone_name, timeout_val=60):
"""
Runs the single official milestone test script with the given 'timeout_val' (in seconds).
"""
milestones_collection = db['new_milestones']
milestone_script = milestones_collection.find_one({"milestone": milestone_name})
default_metrics = {
"insert_time": 0,
"update_time": 0,
"select_time": 0,
"agg_time": 0,
"delete_time": 0
}
def default_failure(message):
tests = {"Test Execution": f"Failed: {message}"}
return default_metrics, tests, 0, 1
if not milestone_script:
print("Milestone script not found for milestone:", milestone_name)
return default_failure("Milestone script not found.")
script_code = milestone_script['code']
tester_script_path = os.path.join(extract_path, 'tester.py')
try:
with open(tester_script_path, 'w') as f:
f.write(script_code)
except Exception as e:
print("Error writing tester.py:", e)
return default_failure("Could not write tester.py file.")
env = os.environ.copy()
env['PYTHONPATH'] = lstore_path + os.pathsep + env.get('PYTHONPATH', '')
try:
result = subprocess.run(
["python", tester_script_path],
capture_output=True,
text=True,
env=env,
cwd=extract_path,
timeout=timeout_val
)
except subprocess.TimeoutExpired:
print("Tester script timed out.")
return default_failure("Test execution timed out.")
except Exception as e:
print("Subprocess error:", e)
return default_failure(f"Subprocess error: {e}")
if result.returncode != 0:
print("Tester script stderr:", result.stderr)
error_message = result.stderr.strip() or "Test execution failed with non-zero return code."
return default_failure(error_message)
try:
output = json.loads(result.stdout)
except json.JSONDecodeError:
print("Invalid JSON tester output:", result.stdout)
return default_failure("Invalid JSON output from tester script.")
tests_out = output.get("tests", {})
if "count" not in output or "total" not in output:
total = len(tests_out)
count = sum(1 for outcome in tests_out.values() if not outcome.startswith("Error"))
else:
count = output["count"]
total = output["total"]
results_out = output.get("results", default_metrics)
results_out = {
k: round(v, 3) if isinstance(v, (int, float)) else v
for k, v in results_out.items()
}
return results_out, tests_out, count, total
def _extract_zip_bytes_to_folder(zip_bytes: bytes, lstore_path: str) -> None:
os.makedirs(lstore_path, exist_ok=True)
with zipfile.ZipFile(BytesIO(zip_bytes)) as zip_file:
top_level_dirs = set()
for name in zip_file.namelist():
parts = name.split('/')
if len(parts) > 0 and parts[0]:
top_level_dirs.add(parts[0])
if len(top_level_dirs) == 1:
folder_name = list(top_level_dirs)[0]
for member in zip_file.namelist():
member_path = os.path.relpath(member, folder_name)
if member_path == '.':
continue
target_path = os.path.join(lstore_path, member_path)
if member.endswith('/'):
os.makedirs(target_path, exist_ok=True)
else:
os.makedirs(os.path.dirname(target_path), exist_ok=True)
with open(target_path, 'wb') as f:
f.write(zip_file.read(member))
else:
zip_file.extractall(lstore_path)
def run_job(job_id: str, params: Dict[str, Any]) -> None:
try:
jobs_collection.update_one(
{"_id": job_id},
{"$set": {"status": "running", "updated_at": datetime.utcnow()}}
)
milestone = params["milestone"]
timeout_val = params["timeout_val"]
ai_timeout_val = params["ai_timeout_val"]
ai_param = params["ai_param"]
submission_name = params["submission_name"]
file_bytes: Optional[bytes] = params.get("file_bytes")
github_repo: Optional[str] = params.get("github_repo")
overall_start = time.time()
unique_id = uuid.uuid4().hex
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
unique_folder_name = f"lstore_eval_{timestamp}_{unique_id}"
extract_path = os.path.join(SUBMISSIONS_DIR, unique_folder_name)
os.makedirs(extract_path, exist_ok=True)
# 1) Extract or clone
if file_bytes:
lstore_path = os.path.join(extract_path, "lstore")
_extract_zip_bytes_to_folder(file_bytes, lstore_path)
elif github_repo:
lstore_path = os.path.join(extract_path, "repo")
subprocess.check_call(["git", "clone", github_repo, lstore_path])
else:
raise RuntimeError("No valid file or GitHub repository provided.")
# 2) Run milestone tests
results, m_tests, m_count, total = milestone_tests(
extract_path,
lstore_path,
milestone,
timeout_val
)
# 3) Optionally run AI checks
if ai_param:
ai_results = asyncio.run(run_ai_tests(lstore_path, ai_timeout=ai_timeout_val))
else:
ai_results = {}
# 4) Commit stats
commit_stats = extract_commit_stats(lstore_path)
overall_end = time.time()
total_subprocess_time = round(overall_end - overall_start, 3)
final_output = {
"submission_name": submission_name,
"milestone": milestone,
"tests": m_tests,
"passed": m_count,
"total_tests": total,
"performance_results": results,
"ai_tests": ai_results,
"commit_stats": commit_stats,
"subprocess_total_time": total_subprocess_time
}
# 5) Store on ResilientDB
tx_id = store_on_resilientdb(final_output)
if tx_id:
final_output["resilientdb_tx_id"] = tx_id
# 6) Insert into Mongo
insert_result = db["new_lstore"].insert_one(dict(final_output))
final_output["_id"] = str(insert_result.inserted_id)
# 7) Mark Job Done
jobs_collection.update_one(
{"_id": job_id},
{"$set": {
"status": "done",
"tx_id": tx_id,
"finished_at": datetime.utcnow(),
"mongo_id": final_output["_id"]
}}
)
except Exception as e:
# Mark Failure
jobs_collection.update_one(
{"_id": job_id},
{"$set": {
"status": "error",
"error": str(e),
"finished_at": datetime.utcnow()
}}
)
POST_TRANSACTION_MUTATION = gql(f"""
mutation postTxn($asset: JSONScalar!) {{
postTransaction(
data: {{
operation: "CREATE",
amount: 100,
signerPublicKey: "{resdb_public_key}",
signerPrivateKey: "{resdb_private_key}",
recipientPublicKey: "{resdb_recipient_key}",
asset: $asset
}}
) {{
id
}}
}}
""")
async def _store_on_resilientdb_async(result_json):
transport = AIOHTTPTransport(url=f"{resdb_url}/graphql")
client = Client(transport=transport, fetch_schema_from_transport=False)
asset_payload = {"data": result_json}
try:
response = await client.execute_async(
POST_TRANSACTION_MUTATION,
variable_values={"asset": asset_payload},
)
return response.get("postTransaction", {}).get("id")
except Exception as e:
print(f"GraphQL Mutation Error: {e}")
return None
def store_on_resilientdb(result_json):
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(_store_on_resilientdb_async(result_json))
except Exception as e:
print("Error storing on resilientdb:", e)
return None
@app.route('/results/<transaction_id>', methods=['GET'])
def get_results_transaction(transaction_id):
query_str = f'''
query {{
getTransaction(id: "{transaction_id}") {{
id
asset
}}
}}
'''
try:
response = requests.post(f"{resdb_url}/graphql", json={"query": query_str})
if response.status_code == 200:
data = response.json()
asset_data = data.get("data", {}).get("getTransaction", {}).get("asset", {})
return jsonify({
"resilientdb_tx_id": transaction_id,
"resilientdb_result": asset_data
})
else:
return jsonify({"error": "Error fetching transaction data from resilientdb."}), 400
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/leaderboard', methods=['GET'])
def leaderboard():
"""
Displays each milestone-specific submission, sorted by:
- Highest 'passed' first,
- Then minimal 'total_time' ascending.
Usage: GET /leaderboard?milestone=<milestoneName>
"""
milestone = request.args.get("milestone")
if not milestone:
return jsonify({"error": "Missing milestone param"}), 400
# Query only docs matching that milestone:
docs = list(db["new_lstore"].find({"milestone": milestone}))
leaderboard_data = []
for d in docs:
submission_name = d.get("submission_name", "Unnamed Submission")
passed = d.get("passed", 0)
total_tests = d.get("total_tests", 0)
tx_id = d.get("resilientdb_tx_id", None)
total_time = d.get("subprocess_total_time", 0)
perf = d.get("performance_results", {})
# Summation of times
perf_sum = 0
for key, val in perf.items():
if key.endswith("_time") and isinstance(val, (int, float)):
perf_sum += val
entry = {
"name": submission_name,
"count": passed,
"total": total_tests,
"total_time": total_time,
"tx_id": tx_id
}
leaderboard_data.append(entry)
# Sort: 1) passed descending, 2) total_time ascending
leaderboard_data.sort(key=lambda x: (-x["count"], x["total_time"]))
return jsonify(leaderboard_data)
@app.route('/jobs/<job_id>', methods=['GET'])
def get_job(job_id: str):
doc = jobs_collection.find_one({"_id": job_id})
if not doc:
return jsonify({"error": "Job not found"}), 404
resp = {"job_id": job_id, "status": doc.get("status", "unknown")}
if doc.get("status") == "done":
resp["tx_id"] = doc.get("tx_id")
resp["mongo_id"] = doc.get("mongo_id")
if doc.get("status") == "error":
resp["error"] = doc.get("error", "unknown error")
return jsonify(resp)
@app.route('/results', methods=['POST'])
def show_results():
milestone = request.form.get('milestone')
timeout_param = request.form.get('timeout')
file = request.files.get('file')
github_repo = request.form.get('github_repo')
ai_param = request.form.get('ai', '0').lower() == '1'
extended_param = request.form.get('extended', '0')
submission_name = request.form.get('submission_name') or generate_unique_name()
# timeout (minutes -> seconds)
try:
timeout_val = float(timeout_param) * 60 if timeout_param else 60
except:
timeout_val = 60
try:
ai_timeout_val = float(timeout_param) * 60 if timeout_param else 300
except:
ai_timeout_val = 300
if not milestone:
return jsonify({"error": "No milestone provided."}), 400
# milestone config check
if milestone not in MILESTONE_CONFIG:
return jsonify({"error": f"Milestone '{milestone}' is not recognized in shared config."}), 400
if not MILESTONE_CONFIG[milestone]["enabled"]:
return jsonify({"error": f"Milestone '{milestone}' is disabled in shared config."}), 400
# extended mapping
if extended_param == "1":
if MILESTONE_CONFIG[milestone]["extended_enabled"]:
milestone = f"{milestone}_extended"
else:
return jsonify({"error": f"Extended version of '{milestone}' is not enabled."}), 400
# Zip or Git
file_bytes = None
if file and file.filename and file.filename.endswith(".zip"):
file_bytes = file.read()
elif not github_repo:
return jsonify({"error": "No valid file or GitHub repository provided."}), 400
# Create Job
job_id = uuid.uuid4().hex
jobs_collection.insert_one({
"_id": job_id,
"status": "queued",
"created_at": datetime.utcnow(),
"milestone": milestone,
"ai": ai_param,
"timeout_val": timeout_val,
"ai_timeout_val": ai_timeout_val,
})
params = {
"milestone": milestone,
"timeout_val": timeout_val,
"ai_timeout_val": ai_timeout_val,
"file_bytes": file_bytes,
"github_repo": github_repo,
"ai_param": ai_param,
"submission_name": submission_name,
}
spawn_thread(run_job, job_id, params)
# Return the job_id first
return jsonify({"job_id": job_id, "api_version": "async-v1"}), 202
'''
@app.route('/results', methods=['GET', 'POST'])
def show_results():
"""
Main route to run tests and store the results.
"""
# Start timing now (for total sub_process time).
overall_start = time.time()
if request.method == 'POST':
milestone = request.form.get('milestone')
timeout_param = request.form.get('timeout')
file = request.files.get('file')
github_repo = request.form.get('github_repo')
ai_param = request.form.get('ai', '0').lower() == '1'
extended_param = request.form.get('extended', '0')
submission_name = request.form.get('submission_name')
else:
milestone = request.args.get('milestone')
timeout_param = request.args.get('timeout')
file = None
github_repo = None
ai_param = False
extended_param = request.args.get('extended', '0')
submission_name = None
if not submission_name:
submission_name = generate_unique_name()
# -- Convert user-provided test timeout (in minutes) to seconds
try:
if timeout_param:
timeout_val = float(timeout_param) * 60
else:
timeout_val = 60
except:
timeout_val = 60
# -- Convert user-provided AI test timeout (in seconds)
try:
if timeout_param:
ai_timeout_val = float(timeout_param) * 60
else:
ai_timeout_val = 300
except:
ai_timeout_val = 300
if not milestone:
return jsonify({"error": "No milestone provided."}), 400
# ====================== USE MILESTONE_CONFIG ======================
# Ensure the milestone is recognized
if milestone not in MILESTONE_CONFIG:
return jsonify({"error": f"Milestone '{milestone}' is not recognized in shared config."}), 400
# Check if this milestone is enabled
if not MILESTONE_CONFIG[milestone]["enabled"]:
return jsonify({"error": f"Milestone '{milestone}' is disabled in shared config."}), 400
# If extended is 'true', verify extended is allowed
if extended_param == "1":
if MILESTONE_CONFIG[milestone]["extended_enabled"]:
# e.g. use "milestone1_extended"
milestone = f"{milestone}_extended"
else:
return jsonify({"error": f"Extended version of '{milestone}' is not enabled."}), 400
# =================================================================
unique_id = uuid.uuid4().hex
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
unique_folder_name = f"lstore_eval_{timestamp}_{unique_id}"
extract_path = os.path.join(SUBMISSIONS_DIR, unique_folder_name)
os.makedirs(extract_path, exist_ok=True)
# 1) Extract or clone user-submitted code
if file and file.filename.endswith('.zip'):
lstore_path = os.path.join(extract_path, 'lstore')
os.makedirs(lstore_path, exist_ok=True)
with zipfile.ZipFile(BytesIO(file.read())) as zip_file:
top_level_dirs = set()
for name in zip_file.namelist():
parts = name.split('/')
if len(parts) > 0 and parts[0]:
top_level_dirs.add(parts[0])
if len(top_level_dirs) == 1:
folder_name = list(top_level_dirs)[0]
for member in zip_file.namelist():
member_path = os.path.relpath(member, folder_name)
if member_path == '.':
continue
target_path = os.path.join(lstore_path, member_path)
if member.endswith('/'):
os.makedirs(target_path, exist_ok=True)
else:
os.makedirs(os.path.dirname(target_path), exist_ok=True)
with open(target_path, 'wb') as f:
f.write(zip_file.read(member))
else:
zip_file.extractall(lstore_path)
elif github_repo:
# Clone directly into extract_path
lstore_path = extract_path
try:
subprocess.check_call(["git", "clone", github_repo, lstore_path])
except Exception as e:
return jsonify({"error": f"Git clone failed: {e}"}), 400
else:
return jsonify({"error": "No valid file or GitHub repository provided."}), 400
# 2) Run milestone tests
results, m_tests, m_count, total = milestone_tests(
extract_path,
lstore_path,
milestone,
timeout_val
)
# 3) Optionally run AI checks
if ai_param:
ai_results = asyncio.run(run_ai_tests(lstore_path, ai_timeout=ai_timeout_val))
else:
ai_results = {}
# 4) Extract commit stats
commit_stats = extract_commit_stats(extract_path)
if github_repo:
repo_stats = extract_commit_stats(lstore_path)
commit_stats["github_repo_commits"] = repo_stats.get("local_git_commits", [])
merged = merge_contributors(
commit_stats.get("contributors", []),
repo_stats.get("contributors", [])
)
commit_stats["contributors"] = merged
# Stop timing now
overall_end = time.time()
total_subprocess_time = round(overall_end - overall_start, 3)
# 5) Prepare final result
final_output = {
"submission_name": submission_name,
"milestone": milestone,
"tests": m_tests,
"passed": m_count,
"total_tests": total,
"performance_results": results, # e.g. insert_time, update_time, etc.
"ai_tests": ai_results,
"commit_stats": commit_stats,
"subprocess_total_time": total_subprocess_time
}
# 6) Store on ResilientDB
tx_id = store_on_resilientdb(final_output)
if tx_id:
final_output["resilientdb_tx_id"] = tx_id
# 7) Insert into Mongo
insert_result = db["new_lstore"].insert_one(dict(final_output))
final_output["_id"] = str(insert_result.inserted_id)
return jsonify(final_output)
'''
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7200, debug=True)