-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathwatchtower.py
More file actions
1707 lines (1532 loc) · 64.5 KB
/
Copy pathwatchtower.py
File metadata and controls
1707 lines (1532 loc) · 64.5 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 api.logging_bootstrap # noqa: F401 # configures JSON logging before anything logs
import gc
import re
import os
import uuid
import time
import gzip
import pybase64 as base64
import asyncio
import aiohttp
import socket
import struct
import random
import hashlib
import orjson as json
import secrets
import traceback
import tempfile
from contextlib import asynccontextmanager
from loguru import logger
from api.log import install_asyncio_exception_handler
from api.config import settings
from api.util import (
decrypt_instance_response,
encrypt_instance_request,
semcomp,
)
from api.database import get_session
from api.chute.schemas import Chute
from api.image.schemas import Image
from api.exceptions import EnvdumpMissing
from sqlalchemy import text, update, func, select
from sqlalchemy.orm import joinedload, selectinload
import api.database.orms # noqa
import api.miner_client as miner_client
from api.instance.schemas import Instance, LaunchConfig
from api.instance.util import purge, purge_and_notify # noqa: F401
TCP_STATES = {
"01": "ESTABLISHED",
"02": "SYN_SENT",
"03": "SYN_RECV",
"04": "FIN_WAIT1",
"05": "FIN_WAIT2",
"06": "TIME_WAIT",
"07": "CLOSE",
"08": "CLOSE_WAIT",
"09": "LAST_ACK",
"0A": "LISTEN",
"0B": "CLOSING",
"0C": "NEW_SYN_RECV",
}
# Short lived chutes (probably just to get bounties).
SHORT_LIVED_CHUTES = """
SELECT instance_audit.chute_id AS chute_id, EXTRACT(EPOCH FROM MAX(instance_audit.deleted_at) - MIN(instance_audit.created_at)) AS lifetime
FROM instance_audit
LEFT OUTER JOIN chutes ON instance_audit.chute_id = chutes.chute_id
WHERE chutes.name IS NULL
AND deleted_at >= now() - interval '7 days'
GROUP BY instance_audit.chute_id
HAVING EXTRACT(EPOCH FROM MAX(instance_audit.deleted_at) - MIN(instance_audit.created_at)) <= 86400
"""
def use_encrypted_slurp(chutes_version: str) -> bool:
"""
Check if the chutes version uses encrypted slurp responses or not.
"""
if not chutes_version:
return False
major, minor, bug = chutes_version.split(".")[:3]
encrypted_slurp = False
if major == "0" and int(minor) >= 2 and (int(minor) > 2 or int(bug) >= 20):
encrypted_slurp = True
return encrypted_slurp
async def load_chute_instances(chute_id):
"""
Get all instances of a chute.
"""
async with get_session() as session:
query = (
select(Instance)
.join(Instance.config)
.where(
Instance.chute_id == chute_id,
Instance.active.is_(True),
Instance.verified.is_(True),
LaunchConfig.env_type != "tee", # Exclude TEE
)
.options(joinedload(Instance.nodes))
)
instances = (await session.execute(query)).unique().scalars().all()
return instances
async def do_slurp(instance, payload, encrypted_slurp):
"""
Slurp a remote file.
"""
enc_payload, iv = encrypt_instance_request(json.dumps(payload), instance)
path, _ = encrypt_instance_request("/_slurp", instance, hex_encode=True)
async with miner_client.post(
instance.miner_hotkey,
f"/{path}",
enc_payload,
instance=instance,
timeout=15.0,
) as resp:
if resp.status == 404:
logger.warning(
f"Failed filesystem check with 404 for {payload=}: "
f"{instance.miner_hotkey=} {instance.instance_id=} {instance.chute_id=}"
)
return None
if encrypted_slurp:
resp_data = (await resp.json())["json"]
decrypted = decrypt_instance_response(resp_data, instance, iv=iv)
return base64.b64decode(json.loads(decrypted)["contents"])
return base64.b64decode(await resp.text())
async def get_hf_content(model, revision, filename) -> tuple[str, str]:
"""
Get the content of a specific model file from huggingface.
"""
cache_key = f"hfdata:{model}:{revision}:{filename}"
local_key = str(uuid.uuid5(uuid.NAMESPACE_OID, cache_key))
cached = await settings.redis_client.get(cache_key)
if cached and os.path.exists(f"/tmp/{local_key}"):
with open(f"/tmp/{local_key}", "r") as infile:
return cached.decode(), infile.read()
url = f"https://huggingface.co/{model}/resolve/{revision}/{filename}"
try:
async with aiohttp.ClientSession(raise_for_status=False) as session:
async with session.get(url) as resp:
resp.raise_for_status()
content = await resp.read()
digest = hashlib.sha256(content).hexdigest()
await settings.redis_client.set(cache_key, digest)
with open(f"/tmp/{local_key}", "w") as outfile:
outfile.write(content.decode())
return digest, content.decode()
except Exception as exc:
logger.error(f"Error checking HF file content: {url} exc={exc}")
return None, None
async def check_weight_files(
encrypted_slurp,
model,
revision,
instances,
weight_map,
hard_failed,
soft_failed,
max_duration=25.0,
):
"""
Check the individual weight files.
"""
to_check = [
instance
for instance in instances
if instance not in hard_failed and instance not in soft_failed
]
if not to_check:
return
weight_files = set()
for layer, path in weight_map.get("weight_map", {}).items():
weight_files.add(path)
if not weight_files:
return
# Select a single random file to check.
path = random.choice(list(weight_files))
file_size = 0
size_key = f"hfsize:{model}:{revision}:{path}"
cached = await settings.redis_client.get(size_key)
if cached:
file_size = int(cached.decode())
else:
try:
async with aiohttp.ClientSession() as session:
url = f"https://huggingface.co/{model}/resolve/{revision}/{path}"
async with session.head(url) as resp:
content_length = resp.headers.get("x-linked-size")
if content_length:
logger.info(f"Size of {model} -> {path}: {content_length}")
file_size = int(content_length)
await settings.redis_client.set(size_key, content_length)
else:
logger.warning(f"Could not determine size of {model} -> {path}")
return
except Exception as exc:
logger.error(f"Error checking HF for {model=} {revision=} {path=}: {str(exc)}")
return
# Now a random offset.
start_byte = 0
end_byte = min(file_size, random.randint(25, 500))
if file_size:
check_size = min(file_size - 1, random.randint(100, 500))
start_byte = random.randint(0, file_size - check_size)
end_byte = start_byte + check_size
expected_digest = None
try:
async with aiohttp.ClientSession() as session:
url = f"https://huggingface.co/{model}/resolve/{revision}/{path}"
async with session.get(
url, headers={"Range": f"bytes={start_byte}-{end_byte - 1}"}
) as resp:
content = await resp.read()
expected_digest = hashlib.sha256(content).hexdigest()
except Exception as exc:
logger.error(f"Error checking HF for {model=} {revision=} and {path=}: {str(exc)}")
return
# Verify each instance has the same.
logger.info(
f"Checking {path} bytes {start_byte}:{end_byte} of model {model} revision {revision}"
)
digest_counts = {}
incorrect = []
for instance in to_check:
nice_name = model.replace("/", "--")
payload = {
"path": f"/cache/hub/models--{nice_name}/snapshots/{revision}/{path}",
"start_byte": start_byte,
"end_byte": end_byte,
}
try:
started_at = time.time()
data = await do_slurp(instance, payload, encrypted_slurp)
duration = time.time() - started_at
if data is None:
hard_failed.append(instance)
continue
digest = hashlib.sha256(data).hexdigest()
if digest not in digest_counts:
digest_counts[digest] = 0
digest_counts[digest] += 1
if digest != expected_digest:
logger.warning(
f"Digest of {path} on {instance.instance_id=} of {model} is incorrect: {expected_digest} vs {digest}"
)
incorrect.append(instance)
else:
logger.success(
f"Digest of {path} on {instance.instance_id=} of {model} is correct: [{start_byte}:{end_byte}] {expected_digest} {duration=}"
)
if duration > max_duration:
logger.warning(
f"Duration to fetch model weight random offset exceeded expected duration: {max_duration=} "
f"{instance.instance_id=} {instance.miner_hotkey=} {path=} {duration=}"
)
soft_failed.append(instance)
except Exception as exc:
logger.warning(
f"Unhandled exception checking {instance.instance_id}: {exc}\n{traceback.format_exc()}"
)
soft_failed.append(instance)
if incorrect:
remaining = [i for i in to_check if i not in [incorrect + soft_failed + hard_failed]]
if not remaining:
logger.warning("No instances would remain after purging incorrect weights!")
return
hotkeys = set([inst.miner_hotkey for inst in incorrect])
if len(digest_counts) == 1 and len(hotkeys) >= 2:
logger.warning(
f"Huggingface digest mismatch, but all miners are in consensus: {expected_digest=} for {path} of {model}"
)
else:
for inst in incorrect:
hard_failed.append(inst)
async def check_llm_weights(chute, instances):
"""
Check the model weights for vllm (and sglang) templated chutes.
"""
if not instances:
logger.warning(f"No instances to check: {chute.name}")
return [], []
chute_id = chute.chute_id
# XXX disabled for now, chute name mismatch (intentional)
if chute_id == "561e4875-254d-588f-a36f-57c9cdef8961":
return [], []
# Revision will need to be a requirement in the future, and at that point
# it can be an attribute on the chute object rather than this janky regex.
if (revision := chute.revision) is None:
revision_match = re.search(
r"(?:--revision |(?:^\s+|,\s*)revision=\")([a-f0-9]{40})", chute.code, re.MULTILINE
)
if revision_match:
revision = revision_match.group(1)
# Could call out to HF and list all revisions and check for any,
# but revision for new chutes is a required parameter now...
if not revision:
logger.warning(f"No revision to check: {chute.name}")
return [], []
# Chute name exceptions, e.g. moonshot kimi k2 with 75k ctx on b200s.
model_match = re.search(r"^\s*model_name\s*=\s*['\"]([^'\"]+)['\"]", chute.code, re.MULTILINE)
model_name = chute.name if not model_match else model_match.group(1)
logger.info(f"Checking {chute.chute_id=} {model_name=} for {revision=}")
encrypted_slurp = use_encrypted_slurp(chute.chutes_version)
# Test each instance.
hard_failed = []
soft_failed = []
instances = await load_chute_instances(chute_id)
if not instances:
return [], []
# First we'll check the primary config files, then we'll test the weights from the map.
target_paths = [
"model.safetensors.index.json",
"config.json",
]
max_durations = {"model.safetensors.index.json": 90}
weight_map = None
for target_path in target_paths:
max_duration = max_durations.get(target_path) or 35.0
incorrect = []
digest_counts = {}
expected_digest, expected_content = await get_hf_content(model_name, revision, target_path)
if not expected_digest:
# Could try other means later on but for now treat as "OK".
logger.warning(
f"Failed to check huggingface for {target_path} on {model_name} {revision=}"
)
continue
if expected_content and target_path == "model.safetensors.index.json":
weight_map = json.loads(expected_content)
for instance in instances:
nice_name = model_name.replace("/", "--")
payload = {"path": f"/cache/hub/models--{nice_name}/snapshots/{revision}/{target_path}"}
try:
started_at = time.time()
data = await do_slurp(instance, payload, encrypted_slurp)
duration = time.time() - started_at
if data is None:
hard_failed.append(instance)
continue
digest = hashlib.sha256(data).hexdigest()
if digest not in digest_counts:
digest_counts[digest] = 0
digest_counts[digest] += 1
if expected_digest and expected_digest != digest:
logger.warning(
f"Digest of {target_path} on {instance.instance_id=} of {model_name} "
f"is incorrect: {expected_digest} vs {digest}"
)
incorrect.append(instance)
logger.info(
f"Digest of {target_path} on {instance.instance_id=} of {model_name}: {digest} {duration=}"
)
if duration > max_duration:
logger.warning(
f"Duration to fetch model weight map exceeded expected duration: {max_duration=} "
f"{instance.instance_id=} {instance.miner_hotkey=} {target_path=} {duration=}"
)
soft_failed.append(instance)
except Exception as exc:
logger.warning(
f"Unhandled exception checking {instance.instance_id}: {exc}\n{traceback.format_exc()}"
)
soft_failed.append(instance)
# Just out of an abundance of caution, we don't want to deleting everything
# if for some reason huggingface has some mismatch but all miners report
# exactly the same thing.
if incorrect:
remaining = [i for i in instances if i not in [incorrect + soft_failed + hard_failed]]
if not remaining:
logger.warning("No instances would remain after purging incorrect weights!")
return
hotkeys = set([inst.miner_hotkey for inst in incorrect])
if len(digest_counts) == 1 and len(hotkeys) >= 2:
logger.warning(
f"Huggingface digest mismatch, but all miners are in consensus: {expected_digest=} for {target_path} of {model_name}"
)
else:
for inst in incorrect:
hard_failed.append(inst)
# Now check the actual weights.
if weight_map:
await check_weight_files(
encrypted_slurp, model_name, revision, instances, weight_map, hard_failed, soft_failed
)
return hard_failed, soft_failed
async def check_live_code(instance, chute, encrypted_slurp) -> bool:
"""
Check the running command.
"""
payload = {"path": "/proc/1/cmdline"}
data = await do_slurp(instance, payload, encrypted_slurp)
if not data:
logger.warning(f"Instance returned no data on proc check: {instance.instance_id}")
return False
# Compare to expected command.
command_line = data.decode().replace("\x00", " ").strip()
command_line = re.sub(r"([^ ]+/)?python3?(\.[0-9]+)?", "python", command_line.strip())
command_line = re.sub(r"([^ ]+/)?chutes\b", "chutes", command_line)
seed = (
None if semcomp(chute.chutes_version or "0.0.0", "0.3.0") >= 0 else instance.nodes[0].seed
)
expected = get_expected_command(chute, instance.miner_hotkey, seed)
if command_line != expected:
logger.error(
f"Failed PID 1 lookup evaluation: {instance.instance_id=} {instance.miner_hotkey=}:\n\t{command_line}\n\t{expected}"
)
return False
# Double check the code.
payload = {"path": f"/app/{chute.filename}"}
code = await do_slurp(instance, payload, encrypted_slurp)
if code != chute.code.encode():
logger.error(
f"Failed code slurp evaluation: {instance.instance_id=} {instance.miner_hotkey=}:\n{code}"
)
return False
logger.success(
f"Code and proc validation success: {instance.instance_id=} {instance.miner_hotkey=}"
)
return True
async def check_ping(chute, instance):
"""
Single instance ping test.
"""
expected = str(uuid.uuid4())
payload, iv = encrypt_instance_request(json.dumps({"foo": expected}), instance)
path, _ = encrypt_instance_request("/_ping", instance, hex_encode=True)
async with miner_client.post(
instance.miner_hotkey,
f"/{path}",
payload,
instance=instance,
timeout=10.0,
) as resp:
raw_content = await resp.read()
resp_data = json.loads(raw_content)
decrypted = decrypt_instance_response(resp_data["json"], instance, iv)
if semcomp(instance.chutes_version or "0.0.0", "0.5.5") >= 0:
decrypted = gzip.decompress(decrypted)
pong = json.loads(decrypted)["foo"]
if pong != expected:
logger.warning(f"Incorrect challenge response to ping: {pong=} vs {expected=}")
return False
logger.success(f"Instance {instance.instance_id=} of {chute.name} ping success: {pong=}")
return True
async def check_pings(chute, instances) -> list:
"""
Simple ping test.
"""
if not instances:
return []
failed = []
for instance in instances:
try:
if not await check_ping(chute, instance):
failed.append(instance)
except Exception as exc:
logger.warning(
f"Unhandled ping exception on instance {instance.instance_id} of {chute.name}: {exc}"
)
failed.append(instance)
return failed
async def check_commands(chute, instances) -> list:
"""
Check the command being used to run a chute on each instance.
"""
if not instances:
return [], []
encrypted = use_encrypted_slurp(chute.chutes_version)
if not encrypted:
logger.info(f"Unable to check command: {chute.chutes_version=} for {chute.name}")
return [], []
hard_failed = []
soft_failed = []
for instance in instances:
try:
if not await check_live_code(instance, chute, encrypted):
hard_failed.append(instance)
except Exception as exc:
logger.warning(f"Unhandled exception checking command {instance.instance_id=}: {exc}")
soft_failed.append(instance)
return hard_failed, soft_failed
async def increment_soft_fail(instance, chute):
"""
Increment soft fail counts and purge if limit is reached.
"""
fail_key = f"watchtower:fail:{instance.instance_id}"
fail_count = await settings.redis_client.incr(fail_key)
await settings.redis_client.expire(fail_key, 3600)
if fail_count and fail_count >= 4:
logger.warning(
f"Instance {instance.instance_id} "
f"miner {instance.miner_hotkey} "
f"chute {chute.name} reached max soft fails: {fail_count}"
)
await purge_and_notify(
instance, reason=f"watchtower - max consecutive soft fails ({fail_count})"
)
def get_expected_command(chute, miner_hotkey: str, seed: int = None):
"""
Get the command line for a given instance.
"""
# New chutes run format expects a JWT and TLS key/cert, but not graval seed.
if semcomp(chute.chutes_version or "0.0.0", "0.3.0") >= 0:
parts = [
"python",
"chutes",
"run",
chute.ref_str,
"--port",
"8000",
"--miner-ss58",
miner_hotkey,
"--validator-ss58",
settings.validator_ss58,
]
return " ".join(parts).strip()
# Legacy format.
return " ".join(
[
"python",
"chutes",
"run",
chute.ref_str,
"--port",
"8000",
"--graval-seed",
str(seed),
"--miner-ss58",
miner_hotkey,
"--validator-ss58",
settings.validator_ss58,
]
).strip()
async def verify_expected_command(dump: dict, chute: Chute, miner_hotkey: str, seed: int = None):
process = dump["all_processes"][0]
assert process["pid"] == 1, "Failed to find chutes comman as PID 1"
assert process["username"] == "chutes", "Not running as chutes user"
command_line = re.sub(r"([^ ]+/)?python3?(\.[0-9]+)?", "python", process["cmdline"]).strip()
command_line = re.sub(r"([^ ]+/)?chutes\b", "chutes", command_line)
expected = get_expected_command(chute, miner_hotkey=miner_hotkey, seed=seed)
assert command_line == expected, f"Unexpected command: {command_line=} vs {expected=}"
logger.success(f"Verified command line: {miner_hotkey=} {command_line=}")
def is_kubernetes_env(
instance: Instance, dump: dict, log_prefix: str, standard_template: str = None
):
# Requires chutes SDK 0.2.53+
if semcomp(instance.chutes_version or "0.0.0", "0.2.53") < 0:
return True
# Lib overrides.
if standard_template:
exclude = {
"UV_SYSTEM_PYTHON",
"PYTHONUNBUFFERED",
"PYTHONIOENCODING",
"PYTHONWARNINGS",
"PYTHONDONTWRITEBYTECODE",
"PYTHONNOUSERSITE",
}
banned = {
"HTTP_PROXY",
"HTTPS_PROXY",
"HF_HUB_DISABLE_SSL_VERIFY",
}
bad = [
key
for key in dump["env"]
if ("python" in key.lower() and key.upper() not in exclude) or key.upper() in banned
]
if bad:
logger.warning(f"{log_prefix} Invalid environment found: PYTHON env override(s): {bad}")
return False
# Verify our LD_PRELOAD (netnanny+logintercept for v3, aegis for v4).
if semcomp(instance.chutes_version or "0.0.0", "0.5.5") >= 0:
if dump["env"].get("LD_PRELOAD") != "/usr/local/lib/chutes-aegis.so":
logger.warning(
f"{log_prefix} Invalid environment found: LD_PRELOAD tampering (expected aegis)"
)
return False
elif semcomp(instance.chutes_version or "0.0.0", "0.3.61") >= 0:
if (
dump["env"].get("LD_PRELOAD")
!= "/usr/local/lib/chutes-netnanny.so:/usr/local/lib/chutes-logintercept.so"
):
logger.warning(f"{log_prefix} Invalid environment found: LD_PRELOAD tampering")
return False
if not dump.get("k8s_info", {}).get("has_service_account"):
logger.warning(
f"{log_prefix} Invalid environment found: k8s (supposed) pod does not have valid service account"
)
return False
if isinstance(dump.get("mounts"), dict):
for mount in dump.get("mounts", {}).get("filesystems", []):
if (
"chutesfs.index" in mount["target"]
or "sglang" in mount["target"]
or "site-packages" in mount["target"]
or re.search(r"^/app\/.*_src", mount["target"])
or "dist-packages" in mount["target"]
):
logger.warning(
f"{log_prefix} Invalid environment found: contains source code or chutesfs index mount"
)
return False
logger.success(f"{log_prefix} kubernetes check passed")
return True
async def check_sglang(instance_id: str, chute: Chute, dump: dict, log_prefix: str):
if "build_sglang_chute(" not in chute.code or chute.standard_template != "vllm":
return True
processes = dump["all_processes"]
# Extract the revision, if present.
if (revision := chute.revision) is None:
revision_match = re.search(
r"(?:--revision |(?:^\s+|,\s*)revision=\")([a-f0-9]{40})", chute.code, re.MULTILINE
)
if revision_match:
revision = revision_match.group(1)
# Chute name exceptions, e.g. moonshot kimi k2 with 75k ctx on b200s.
model_match = re.search(r"^\s*model_name\s*=\s*['\"]([^'\"]+)['\"]", chute.code, re.MULTILINE)
model_name = chute.name if not model_match else model_match.group(1)
found_sglang = False
sglang_process = None
for process in processes:
target_exe = process["exe"] if process["exe"].strip() else process["cmdline"].split(" ")[0]
clean_exe = re.sub(r"([^ ]+/)?python3?(\.[0-9]+)?", "python", target_exe)
cmdline = re.sub(r"([^ ]+/)?python3?(\.[0-9]+)?", "python", process["cmdline"])
if (
clean_exe in ["python", "python3.10", "python3.11", "python3.12"]
and process["username"] == "chutes"
and cmdline.startswith(
f"python -m sglang.launch_server --host 127.0.0.1 --port 10101 --model-path {model_name}"
)
):
if semcomp(chute.chutes_version or "0.0.0", "0.3.48") >= 0:
if "--enable-cache-report" not in cmdline:
logger.warning(f"Cache report not enabled: {cmdline}")
elif "--enable-return-hidden-states" not in cmdline:
logger.warning(f"Hidden states return not enabled: {cmdline}")
else:
found_sglang = True
else:
found_sglang = True
if revision and revision not in cmdline:
found_sglang = False
logger.warning(f"Did not find model revision in SGLang command: {cmdline}")
if found_sglang:
logger.success(f"{log_prefix} found valid SGLang chute: {process=}")
sglang_process = process
break
if not found_sglang:
logger.error(f"{log_prefix} did not find SGLang process, bad: {processes=}")
return False
# Track the process.
current_pid = sglang_process["pid"]
pid_key = f"sglangpid:{instance_id}"
cached = await settings.redis_client.get(pid_key)
if cached:
previous_pid = int(cached)
if previous_pid != current_pid:
logger.error(
f"{log_prefix} primary SGLang PID has changed from {previous_pid=} to {current_pid=}"
)
return False
else:
await settings.redis_client.set(pid_key, f"{current_pid}")
return True
async def check_chute(chute_id):
"""
Check a single chute.
"""
async with get_session() as session:
chute = (
(await session.execute(select(Chute).where(Chute.chute_id == chute_id)))
.unique()
.scalar_one_or_none()
)
if not chute:
logger.warning(f"Chute not found: {chute_id=}")
return
if chute.rolling_update:
logger.warning(f"Chute has a rolling update in progress: {chute_id=}")
return
# Updated environment/code checks.
instances = await load_chute_instances(chute.chute_id)
random.shuffle(instances)
bad_env = set()
if semcomp(chute.chutes_version or "0.0.0", "0.2.53") >= 0 and os.getenv("ENVDUMP_UNLOCK"):
instance_map = {instance.instance_id: instance for instance in instances}
# Load the envdump dump outputs for each.
missing = set(instance_map)
async with get_dumps(instances) as paths:
for path in paths:
failed_envdump = False
if not path:
failed_envdump = True
continue
instance_id = path.split("dump-")[-1].split(".")[0]
missing.discard(instance_id)
instance = instance_map[instance_id]
log_prefix = f"ENVDUMP: {instance.instance_id=} {instance.miner_hotkey=} {instance.chute_id=}"
with open(path) as infile:
dump = json.loads(infile.read())
# Ensure proper k8s env.
if not is_kubernetes_env(instance, dump, log_prefix):
logger.error(f"{log_prefix} is not running a valid kubernetes environment")
failed_envdump = True
# Check SGLang processes.
if not await check_sglang(instance.instance_id, chute, dump, log_prefix):
logger.error(f"{log_prefix} did not find SGLang process, bad...")
failed_envdump = True
# Check the running command.
try:
await verify_expected_command(
dump,
chute,
miner_hotkey=instance.miner_hotkey,
seed=instance.nodes[0].seed,
)
except AssertionError as exc:
logger.error(f"{log_prefix} failed running command check: {exc=}")
failed_envdump = True
except Exception as exc:
logger.error(
f"{log_prefix} unhandled exception checking env dump: {exc=}\n{traceback.format_exc()}"
)
failed_envdump = True
# Delete failed checks.
if failed_envdump:
await purge_and_notify(
instance,
reason="watchtower - failed env dump signature or process checks",
)
bad_env.add(instance.instance_id)
failed_count = await settings.redis_client.incr(
f"envdumpfail:{instance.miner_hotkey}"
)
logger.warning(
f"ENVDUMP: Miner {instance.miner_hotkey} has now failed {failed_count} envdump checks"
)
# if failed_count >= 5:
# async with get_session() as session:
# await session.execute(
# text("""
# UPDATE metagraph_nodes
# SET blacklist_reason = 'Recurring pattern of invalid processes discovered by watchtower.'
# WHERE hotkey = :hotkey
# """),
# {"hotkey": instance.miner_hotkey}
# )
# Filter out the ones we already blacklisted.
instances = [instance for instance in instances if instance.instance_id not in bad_env]
# Ping test.
soft_failed = await check_pings(chute, instances)
# Check the running command.
instances = [instance for instance in instances if instance not in soft_failed]
hard_failed, _soft_failed = await check_commands(chute, instances)
soft_failed += _soft_failed
# Check model weights.
if chute.standard_template == "vllm":
instances = [
instance
for instance in instances
if instance not in soft_failed and instance not in hard_failed
]
_hard_failed, _soft_failed = await check_llm_weights(chute, instances)
hard_failed += _hard_failed
soft_failed += _soft_failed
# Hard failures get terminated immediately.
for instance in hard_failed:
if not instance:
continue
logger.warning(
f"Purging instance {instance.instance_id} "
f"miner {instance.miner_hotkey} "
f"chute {chute.name} due to hard fail"
)
await purge_and_notify(instance, reason="watchtower - hard probe failure")
# Limit "soft" fails to max consecutive failures, allowing some downtime but not much.
for instance in soft_failed:
if not instance:
continue
await increment_soft_fail(instance, chute)
# Update verification time for the ones that succeeded.
to_update = [
instance
for instance in instances
if instance not in soft_failed and instance not in hard_failed
]
if to_update:
async with get_session() as session:
stmt = (
update(Instance)
.where(Instance.instance_id.in_([i.instance_id for i in to_update]))
.values(last_verified_at=func.now())
.execution_options(synchronize_session=False)
)
await session.execute(stmt)
await session.commit()
for inst in to_update:
fail_key = f"watchtower:fail:{inst.instance_id}"
await settings.redis_client.delete(fail_key)
async def check_all_chutes():
"""
Check all chutes and instances, one time.
"""
started_at = int(time.time())
async with get_session() as session:
chute_ids = (await session.execute(select(Chute.chute_id))).unique().scalars().all()
if chute_ids and isinstance(chute_ids[0], tuple):
chute_ids = [chute_id[0] for chute_id in chute_ids]
chute_ids = list(sorted(chute_ids))
for i in range(0, len(chute_ids), 8):
batch = chute_ids[i : i + 8]
logger.info(f"Initializing check of chutes: {batch}")
await asyncio.gather(*[check_chute(chute_id) for chute_id in batch])
delta = int(time.time()) - started_at
logger.info(f"Finished probing all instances of {len(chute_ids)} chutes in {delta} seconds.")
async def generate_confirmed_reports(chute_id, reason):
"""
When a chute is confirmed bad, generate reports for it.
"""
from api.user.service import chutes_user_id
async with get_session() as session:
report_query = text("""
WITH inserted AS (
INSERT INTO reports
(invocation_id, user_id, timestamp, confirmed_at, confirmed_by, reason)
SELECT
parent_invocation_id,
:user_id,
now(),
now(),
:confirmed_by,
:reason
FROM invocations i
WHERE chute_id = :chute_id
AND NOT EXISTS (
SELECT 1 FROM reports r
WHERE r.invocation_id = i.parent_invocation_id
)
ON CONFLICT (invocation_id) DO NOTHING
RETURNING invocation_id
)
SELECT COUNT(*) AS report_count FROM inserted;
""")
count = (
await session.execute(
report_query,
{
"user_id": await chutes_user_id(),
"confirmed_by": await chutes_user_id(),
"chute_id": chute_id,
"reason": reason,
},
)
).scalar()
logger.success(f"Generated {count} reports for chute {chute_id}")
await session.commit()
async def report_short_lived_chutes():
"""
Generate reports for chutes that only existed for a short time, likely from scummy miners to get bounties.
"""
query = text(SHORT_LIVED_CHUTES)
bad_chutes = []
async with get_session() as session:
result = await session.execute(query)
rows = result.fetchall()
for row in rows:
chute_id = row.chute_id
lifetime = row.lifetime
bad_chutes.append(
(chute_id, f"chute was very short lived: {lifetime=}, likely bounty scam")
)
logger.warning(
f"Detected short-lived chute {chute_id} likely part of bounty scam: {lifetime=}"
)
# Generate the reports in separate sessions so we don't have massive transactions.
for chute_id, reason in bad_chutes:
await generate_confirmed_reports(chute_id, reason)
async def procs_check():
"""
Check processes.
"""
while True:
async with get_session() as session:
query = (
select(Instance)
.where(
Instance.verified.is_(True),
Instance.active.is_(True),
)
.options(selectinload(Instance.nodes), selectinload(Instance.chute))
)
batch_size = 10
async for row in await session.stream(query.execution_options(yield_per=batch_size)):
instance = row[0]
if not instance.chutes_version or not re.match(
r"^0\.2\.[3-9][0-9]$", instance.chutes_version
):
continue
skip_key = f"procskip:{instance.instance_id}"
if await settings.redis_client.get(skip_key):
await settings.redis_client.expire(skip_key, 60 * 60 * 24 * 2)
continue
path, _ = encrypt_instance_request("/_procs", instance, hex_encode=True)
try:
async with miner_client.get(
instance.miner_hotkey,
f"/{path}",
purpose="chutes",
instance=instance,
timeout=15.0,
) as resp:
data = await resp.json()
env = data.get("1", {}).get("environ", {})
cmdline = data.get("1", {}).get("cmdline", [])
reason = None
if not cmdline and (not env or "CHUTES_EXECUTION_CONTEXT" not in env):
reason = f"Running an invalid process [{instance.instance_id=} {instance.miner_hotkey=}]: {cmdline=} {env=}"
elif len(cmdline) <= 5 or cmdline[1].split("/")[-1] != "chutes":
reason = f"Running an invalid process [{instance.instance_id=} {instance.miner_hotkey=}]: {cmdline=} {env=}"
if reason:
logger.warning(reason)
await purge_and_notify(
instance, reason="watchtower - miner failed probes"
)
else: