-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathserver.py
More file actions
3046 lines (2711 loc) · 139 KB
/
Copy pathserver.py
File metadata and controls
3046 lines (2711 loc) · 139 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
#!/usr/bin/env python3
"""Tofu Server — Quart + Hypercorn (HTTP/2, ASGI).
App entry point. Uses:
- Quart (async Flask from Pallets) as the application framework
- Hypercorn as the ASGI server with HTTP/2 support
- Auto-generated self-signed TLS for zero-config HTTP/2 in browsers
All existing Flask-style sync route handlers run unchanged in a thread pool.
Usage:
python server.py # HTTPS + HTTP/2 (auto-cert)
python server.py --no-tls # HTTP/1.1 only
python server.py --certfile cert.pem --keyfile key.pem # custom cert
"""
import asyncio
import os
import sys
import json
import logging
import time
import signal
import threading
import faulthandler
# ── Capture C-level fatal signals (SIGSEGV / SIGABRT / SIGFPE / SIGILL / SIGBUS) ──
# These fire on heap corruption (e.g. `munmap_chunk(): invalid pointer`) from
# native extensions like urllib3's response decompressor. Without this the
# abort prints to fd 2 only and we lose the Python stack of every thread.
# Writing to a dedicated file (instead of stderr) ensures the trace survives
# even when stderr is the controlling terminal of a process that's about
# to die. all_threads=True captures every Python thread, not just the
# crashing one — essential for diagnosing concurrent-fetch races.
#
# Dual-sink strategy: write to BOTH the FUSE-backed logs/ (durable across
# box restarts, but may be truncated by the very FUSE stall that caused the
# crash) AND a tmpfs mirror in /dev/shm (immune to FUSE stalls, but lost on
# box reboot). On crash, check /dev/shm first for the clean copy.
_fault_log = None
try:
_FAULT_LOG_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'logs', 'faulthandler.log')
os.makedirs(os.path.dirname(_FAULT_LOG_PATH), exist_ok=True)
_fault_log = open(_FAULT_LOG_PATH, 'a', buffering=1) # line-buffered
_fault_log.write('\n=== faulthandler armed pid=%d at %s ===\n'
% (os.getpid(), time.strftime('%Y-%m-%d %H:%M:%S')))
except OSError:
pass
# Prefer tmpfs for the live faulthandler sink (survives FUSE stalls intact);
# fall back to the FUSE log, then stderr.
_fault_shm_log = None
try:
_FAULT_SHM_PATH = '/dev/shm/tofu_faulthandler_%d.log' % os.getpid()
_fault_shm_log = open(_FAULT_SHM_PATH, 'w', buffering=1)
_fault_shm_log.write('=== faulthandler armed pid=%d at %s ===\n'
% (os.getpid(), time.strftime('%Y-%m-%d %H:%M:%S')))
faulthandler.enable(file=_fault_shm_log, all_threads=True)
except OSError:
_fault_shm_log = None
if _fault_shm_log is None:
# tmpfs unavailable — use the FUSE log (better than nothing)
if _fault_log is not None:
faulthandler.enable(file=_fault_log, all_threads=True)
else:
faulthandler.enable(all_threads=True)
# ── Faulthandler-sink hygiene + event-loop stall detection (pure helpers) ──
# These back the boot-time /dev/shm prune and the loop-stall watchdog wired up
# inside _serve(). Kept at module scope (not nested in _serve) so they are pure
# and unit-testable without a running loop — see tests/test_loop_stall_watchdog.py.
_FAULT_DUMP_PREFIX = 'tofu_faulthandler_'
_FAULT_DUMP_SUFFIX = '.log'
def _pid_alive(pid):
"""Best-effort liveness probe for *pid* (signal 0). Conservative: an
ambiguous OSError (other than 'no such process') reports True so we never
delete a dump whose owner might still be running."""
if not isinstance(pid, int) or pid <= 0:
return False
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except OverflowError:
return False # pid out of representable range → cannot be a live process
except PermissionError:
return True # exists but owned by another user
except OSError:
return True # ambiguous — err on the side of keeping
return True
def _read_instance_lock_entry(lock_path):
"""Read the ``<pid>@<host>`` first line of the single-instance lock file.
Returns ``(pid:int|None, host:str|None)``. A missing/empty/malformed file
yields ``(None, None)`` (or ``(None, host)`` if only the pid is unparseable).
"""
try:
with open(lock_path, 'r') as f:
entry = (f.readline() or '').strip()
except OSError:
return None, None
if not entry or '@' not in entry:
return None, None
pid_str, _, host = entry.partition('@')
host = host.strip() or None
try:
return int(pid_str), host
except (ValueError, TypeError):
return None, host
def _pid_is_live_server(pid):
"""True iff *pid* is alive AND its ``/proc/<pid>/cmdline`` still looks like
our ``server.py``.
A dead pid → False. A live pid whose cmdline is provably NOT ``server.py``
(PID reuse) → False. If liveness or the cmdline cannot be established
(no /proc, permission denied, empty cmdline) this conservatively returns
True so we NEVER reclaim a lock whose owner might still be a running server.
Mirrors stop.sh's ``kill -0`` + ``ps -o args`` server.py check.
"""
if not _pid_alive(pid):
return False
try:
with open('/proc/%d/cmdline' % pid, 'rb') as f:
cmdline = f.read().replace(b'\x00', b' ').decode('utf-8', 'replace')
except (OSError, ValueError):
return True # cannot inspect → assume a live server, refuse to reclaim
if not cmdline.strip():
return True # ambiguous → conservative
return 'server.py' in cmdline
# ── Loop-heartbeat sidecar (cross-process wedge detection for lock reclaim) ──
# A ``flock`` proves neither liveness nor HEALTH: a server whose event loop is
# wedged in a FUSE syscall (the proven root cause of the 5-minute restart
# stalls) is still alive, still ``server.py``, still holds the flock — so
# ``_pid_is_live_server`` reports True and the reclaim refuses, blocking the
# operator's restart. The fix is a second signal: the live loop persists a
# wall-clock heartbeat to a sidecar; a RESTARTING process reads it to tell a
# healthy holder (fresh heartbeat → refuse) from a wedged one (stale → reclaim).
#
# The sidecar lives on LOCAL disk, NOT under data/ (the FUSE mount that
# wedges): the reader runs in the restarting process DURING the exact FUSE
# stall we're detecting and must never block. Local xfs (``/tmp/tofu``) reads
# cannot block, and a loop wedged in a FUSE syscall simply stops REFRESHING
# the local file → its age grows → that IS the wedged signal. Wall-clock (not
# monotonic) because a DIFFERENT process interprets it.
_HEARTBEAT_FILE = 'server.heartbeat'
def _heartbeat_dir():
"""Local-disk directory for the loop-heartbeat sidecar (see block comment).
Overridable via ``TOFU_HEARTBEAT_DIR``; defaults to ``<TOFU_DB_LOCAL_ROOT
or /tmp/tofu>/heartbeat`` so it shares the same POSIX-correct local volume
the DB local-primary split targets.
"""
d = (os.environ.get('TOFU_HEARTBEAT_DIR', '') or '').strip()
if d:
return d
root = (os.environ.get('TOFU_DB_LOCAL_ROOT', '') or '').strip() or '/tmp/tofu'
return os.path.join(root, 'heartbeat')
def _heartbeat_path():
"""Absolute path of the heartbeat sidecar file."""
return os.path.join(_heartbeat_dir(), _HEARTBEAT_FILE)
def _write_heartbeat(pid=None, ts=None, path=None):
"""Atomically stamp ``{pid, ts}`` (wall-clock) into the sidecar.
Best-effort: a wedged loop failing to write is precisely the signal we
want, so a write failure NEVER raises — it just lets the file age. Atomic
(temp + ``os.replace``) so a concurrent reader never sees a half-written
file. Returns True on success, False on any failure.
"""
pid = os.getpid() if pid is None else pid
ts = time.time() if ts is None else ts
path = path or _heartbeat_path()
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = '%s.%d.tmp' % (path, pid)
with open(tmp, 'w') as f:
f.write(json.dumps({'pid': pid, 'ts': ts}))
os.replace(tmp, path)
return True
except (OSError, ValueError, TypeError) as e:
logging.getLogger('server').debug('[Heartbeat] write failed (%s) — '
'letting the sidecar age', e)
return False
def _read_heartbeat(path=None):
"""Read ``(pid:int|None, ts:float|None)`` from the sidecar.
A missing / unreadable / unparseable file yields ``(None, None)`` — the
normal case when no server is running and also the fail-safe for the
reclaim decision (ambiguity → never claim wedge).
"""
path = path or _heartbeat_path()
try:
with open(path) as f:
data = json.loads(f.read() or '{}')
pid = data.get('pid')
ts = data.get('ts')
return (int(pid) if pid is not None else None,
float(ts) if ts is not None else None)
except (OSError, ValueError, TypeError) as e:
logging.getLogger('server').debug('[Heartbeat] read failed/absent: %s', e)
return None, None
def _heartbeat_stale_threshold():
"""Seconds after which a heartbeat proves the loop is wedged.
Conservative: ``max(30s, 3 × TOFU_LOOP_HEARTBEAT_SECS)`` — well beyond any
healthy GC pause or momentary busy stretch, so a genuinely-running server
is never falsely reclaimed.
"""
try:
bump = float(os.environ.get('TOFU_LOOP_HEARTBEAT_SECS', '') or '1')
except (ValueError, TypeError):
bump = 1.0
if bump <= 0:
bump = 1.0
return max(30.0, bump * 3.0)
def _holder_wedge_age(pid, now=None, path=None):
"""Return the heartbeat AGE (seconds) iff the sidecar PROVES *pid*'s event
loop is wedged, else None.
"Proves" = the heartbeat belongs to *pid* (its recorded pid matches, so we
never judge a live server by a stale file from a DIFFERENT process) AND its
wall-clock age exceeds ``_heartbeat_stale_threshold()``. Every ambiguous
case — missing / unparseable file, mismatched pid, or a future-dated ts
(clock skew) — returns None so the caller keeps today's refuse-to-reclaim
behaviour. The age is returned (not just a bool) so the caller can log the
concrete staleness.
"""
hb_pid, hb_ts = _read_heartbeat(path)
if hb_pid is None or hb_ts is None or hb_pid != pid:
return None
now = time.time() if now is None else now
age = now - hb_ts
if age < 0 or age <= _heartbeat_stale_threshold():
return None
return age
def _reclaim_stale_instance_lock(lock_path, hostname, logger):
"""Decide whether a flock-contended instance lock is a STALE *local* lock we
may reclaim, and if so unlink it so a fresh inode can be flock'd.
Robustness rationale (the crux of the OOM-restart bug): ``flock`` is bound
to an open file *description*, NOT to process liveness. When the previous
server is SIGKILL'd (e.g. OOM) its atexit/lock-release never runs, and
orphaned child processes may keep the fd — and thus the flock — open
indefinitely; on a FUSE mount the advisory lock is not reliably released on
unclean death either. So a contended flock does NOT prove "a server is
running". We mirror stop.sh: read the recorded ``<pid>@<host>`` and ONLY
when ``host == this machine`` AND that pid is not a live ``server.py`` do we
``unlink`` the lock path. Unlinking yields a brand-new inode on the retry;
the orphan's surviving fd points at the now-unlinked OLD inode, so its
lingering flock is harmless and our flock on the new inode succeeds.
Cross-host staleness is deliberately NOT handled here (that is the PG
heartbeat-takeover's domain) — a foreign-host lock is left untouched and the
caller refuses to start.
Returns True iff a stale local lock was unlinked (caller should retry the
flock), else False.
"""
pid, host = _read_instance_lock_entry(lock_path)
if pid is None and host is None:
logger.critical('[Lock] contended instance lock has no readable <pid>@<host> entry — '
'refusing to reclaim (a live peer may hold it)')
return False
if host and host != hostname:
logger.critical('[Lock] instance lock held by another host: pid=%s host=%s (we are %s) — '
'refusing to reclaim a foreign lock (cross-host is PG-heartbeat territory)',
pid, host, hostname)
return False
if pid is not None and _pid_is_live_server(pid):
# A live local server.py normally means "genuinely running" — refuse.
# BUT a loop wedged in a FUSE syscall is ALSO live+server.py yet cannot
# serve or release its lock (the 5-minute-restart-stall root cause). The
# heartbeat sidecar is the tie-breaker: only when it PROVES this pid's
# loop has been silent past the stale threshold do we treat the holder
# as wedged and reclaim. Fresh / missing / ambiguous heartbeat → keep
# the refuse (fail-safe: never reclaim a possibly-healthy server).
wedge_age = _holder_wedge_age(pid)
if wedge_age is None:
logger.critical('[Lock] instance lock held by a LIVE local server (pid=%s host=%s) — '
'another instance is genuinely running', pid, host)
return False
logger.critical('[Lock] instance lock held by a WEDGED local server '
'(pid=%s host=%s) — loop heartbeat stale %.1fs (threshold=%.1fs); '
'reclaiming so a fresh instance can start', pid, host,
wedge_age, _heartbeat_stale_threshold())
else:
logger.warning('[Lock] reclaiming stale lock pid=%s host=%s (dead)', pid, host)
try:
os.unlink(lock_path)
except OSError as e:
logger.critical('[Lock] failed to unlink stale lock %s: %s', lock_path, e)
return False
return True
def _acquire_instance_lock(lock_path, logger, hostname=None, allow_reclaim=True):
"""Acquire the exclusive single-instance lock at *lock_path*.
Returns ``(ok, fd)``: ``(True, <open flocked fd>)`` on success — the caller
MUST keep the fd open for the whole process lifetime — or ``(False, None)``
when a live instance genuinely holds it. On a platform without ``fcntl`` /
with an unopenable lock dir it degrades to best-effort ``(True, fd|None)``
so a missing lock never blocks startup.
Self-healing: on flock contention we do NOT assume a live server (see
``_reclaim_stale_instance_lock`` for why). If the recorded owner is a dead
LOCAL pid we unlink the stale lock and retry ONCE on a fresh inode. A
single bounded retry (``allow_reclaim=False``) guarantees no reclaim loop;
if the retry still fails we log CRITICAL and refuse (caller surfaces the
``TOFU_SKIP_LOCK=1`` escape hatch).
"""
if hostname is None:
import socket as _s
hostname = _s.gethostname()
try:
import fcntl
except ImportError:
logger.warning('[Lock] fcntl unavailable on this platform — skipping instance lock')
try:
return True, open(lock_path, 'a+')
except OSError:
return True, None
try:
if not os.path.exists(lock_path):
open(lock_path, 'a').close()
fd = open(lock_path, 'r+')
except OSError as e:
logger.warning('[Lock] cannot open lock file %s (%s) — proceeding without instance lock', lock_path, e)
return True, None
try:
fcntl.flock(fd.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
fd.close()
if allow_reclaim and _reclaim_stale_instance_lock(lock_path, hostname, logger):
ok2, fd2 = _acquire_instance_lock(lock_path, logger, hostname=hostname, allow_reclaim=False)
if ok2 and fd2 is not None:
logger.info('[Lock] reclaimed stale lock and acquired fresh instance lock (pid=%d)', os.getpid())
else:
logger.critical('[Lock] reclaimed stale lock but STILL could not acquire flock — '
'refusing to start. Set TOFU_SKIP_LOCK=1 to override.')
return ok2, fd2
return False, None
try:
fd.seek(0)
fd.truncate()
fd.write('%d@%s\n' % (os.getpid(), hostname))
fd.flush()
except OSError as e:
logger.debug('[Lock] could not stamp lock identity: %s', e)
return True, fd
def _parse_fault_dump_pid(basename):
"""Extract the pid from ``tofu_faulthandler_<pid>.log`` (else None)."""
if not basename.startswith(_FAULT_DUMP_PREFIX) or not basename.endswith(_FAULT_DUMP_SUFFIX):
return None
core = basename[len(_FAULT_DUMP_PREFIX):-len(_FAULT_DUMP_SUFFIX)]
try:
return int(core)
except (ValueError, TypeError):
return None
def _prune_stale_fault_dumps(directory='/dev/shm', keep_basename='',
pid_alive=_pid_alive, logger=None):
"""Delete ``tofu_faulthandler_<pid>.log`` files in *directory* whose pid is
no longer alive. Never touches *keep_basename* (our own live sink) or files
that don't match the naming pattern. Returns the number removed.
server.py opens one such file on every boot but historically never removed
old ones, so the /dev/shm sink accumulated thousands of dead-pid files."""
import glob as _glob
removed = 0
pattern = os.path.join(directory, _FAULT_DUMP_PREFIX + '*' + _FAULT_DUMP_SUFFIX)
for path in _glob.glob(pattern):
base = os.path.basename(path)
if keep_basename and base == keep_basename:
continue
pid = _parse_fault_dump_pid(base)
if pid is None or pid_alive(pid):
continue
try:
os.unlink(path)
removed += 1
except OSError as _rm_err:
if logger is not None:
logger.debug('[LoopWatch] could not prune %s: %s', path, _rm_err)
return removed
def _loop_stall_decide(age, threshold, already_dumped):
"""Pure decision for the loop-stall watchdog.
Given the heartbeat *age* (seconds since the last on-loop bump), the stall
*threshold*, and whether we've *already_dumped* for the current stall
episode, return ``(should_dump, next_already_dumped)``. Emits at most one
dump per contiguous stall episode and re-arms once the loop recovers."""
if threshold <= 0:
return (False, already_dumped) # watchdog disabled
if age <= threshold:
return (False, False) # healthy → re-arm for the next episode
if already_dumped:
return (False, True) # still stalled, already captured
return (True, True) # stalled and not yet captured → dump
def _extract_loop_top_frame(frame, project_root=None):
"""Pure: given the event-loop thread's current frame, return a one-line
``file:line in func`` locator for the STALL culprit.
Walks OUTWARD from the innermost frame and returns the first frame whose
file lives under *project_root* (our own code) — i.e. the deepest
application frame, skipping stdlib/site-packages leaf frames like
``ssl.read`` so the audit line names ``segment_backfill.py:257`` rather
than a generic C-level socket read. Falls back to the innermost frame when
none match (all-stdlib stall). Returns ``''`` when *frame* is None.
Kept pure + arg-injected (no globals) so a unit test can build a synthetic
frame chain and assert the culprit is picked without a real stall.
"""
if frame is None:
return ''
if project_root is None:
project_root = os.path.dirname(os.path.abspath(__file__))
innermost = None
f = frame
while f is not None:
code = f.f_code
fname = code.co_filename
if innermost is None:
innermost = '%s:%d in %s' % (fname, f.f_lineno, code.co_name)
try:
in_project = os.path.abspath(fname).startswith(project_root + os.sep)
except Exception:
in_project = False
if in_project and 'site-packages' not in fname:
return '%s:%d in %s' % (fname, f.f_lineno, code.co_name)
f = f.f_back
return innermost or ''
def _should_arm_ctimer(threshold, sink):
"""Pure gate for the GIL-INDEPENDENT capture path.
``faulthandler.dump_traceback_later`` runs from a dedicated C timer thread
that does NOT acquire the GIL, so it fires even when the loop is wedged
inside a single monolithic GIL-holding C call (the documented ``json.dumps``
/ catastrophic-regex pit) — the exact case the Python-thread watcher, which
must take the GIL to run, is BLIND to. Arm it only when the watchdog is
enabled (*threshold* > 0) AND we have a sink with a real file descriptor
(``dump_traceback_later`` requires an fd — an in-memory buffer has none)."""
if threshold is None or threshold <= 0:
return False
if sink is None:
return False
try:
sink.fileno()
except Exception:
return False
return True
# One-shot boot cleanup: prune dead-pid faulthandler dumps from the tmpfs sink
# so it stays bounded (the file we just opened for THIS pid is preserved).
if _fault_shm_log is not None:
try:
_pruned = _prune_stale_fault_dumps(
directory='/dev/shm',
keep_basename=os.path.basename(_FAULT_SHM_PATH))
if _pruned:
sys.stderr.write('[boot] pruned %d stale faulthandler dump(s) from /dev/shm\n'
% _pruned)
except Exception:
pass # cleanup is best-effort; never block boot on it
# ── Pin mapped pages into RAM (FUSE SIGBUS mitigation) ──
# All .so files (C extensions, libpython, libc) are dlopen'd via mmap with
# demand-paged code segments. When those files live on a FUSE mount, a
# transient stall during a lazy page-in delivers SIGBUS (unrecoverable).
# MCL_CURRENT pins already-mapped pages; MCL_FUTURE pins every future mmap
# at load time, collapsing the dangerous demand-fault window to zero.
#
# BUT pinned pages are unreclaimable and are charged against the cgroup
# memory limit. On a memory-constrained container (e.g. an exported copy
# on a small box) pinning the whole C-extension working set can push RSS
# past memory.max → the OOM killer SIGKILLs the process at boot (a bare
# "Killed" with no traceback). mlockall only HELPS on a FUSE mount and is
# only SAFE with headroom under the cgroup limit, so we gate on both.
# Override: TOFU_MLOCK=1 forces it on, =0 forces it off (default 'auto').
def _tofu_path_is_fuse(_path):
"""Best-effort: True if *_path* sits on a FUSE filesystem (stdlib-only)."""
try:
_path = os.path.abspath(_path)
_best_mp, _best_fstype = '', ''
with open('/proc/self/mountinfo', 'r') as _f:
for _line in _f:
# mountinfo: "... <mount point> ... - <fstype> <source> ..."
_halves = _line.split(' - ')
if len(_halves) != 2:
continue
_left = _halves[0].split()
_right = _halves[1].split()
if len(_left) < 5 or not _right:
continue
_mp, _fstype = _left[4], _right[0]
if (_path == _mp or _path.startswith(_mp.rstrip('/') + '/')) \
and len(_mp) >= len(_best_mp):
_best_mp, _best_fstype = _mp, _fstype
return _best_fstype.startswith('fuse')
except OSError:
return False
def _tofu_cgroup_mem_limit_bytes():
"""cgroup memory limit in bytes, or None if unlimited/unknown (stdlib-only)."""
for _p in ('/sys/fs/cgroup/memory.max', # cgroup v2
'/sys/fs/cgroup/memory/memory.limit_in_bytes'): # cgroup v1
try:
with open(_p, 'r') as _f:
_raw = _f.read().strip()
except OSError:
continue
if _raw == 'max':
return None
try:
_val = int(_raw)
except ValueError:
continue
# cgroup v1 reports a huge sentinel (~PAGE_COUNTER_MAX) for "unlimited"
if _val <= 0 or _val >= (1 << 62):
return None
return _val
return None
def _tofu_should_mlock():
"""Decide whether mlockall is worth it. Returns (do_it, reason)."""
_mode = os.environ.get('TOFU_MLOCK', 'auto').strip().lower()
if _mode in ('0', 'off', 'false', 'no'):
return False, 'disabled via TOFU_MLOCK=%s' % _mode
if _mode in ('1', 'on', 'true', 'yes', 'force'):
return True, 'forced via TOFU_MLOCK=%s' % _mode
# auto: pin only where the SIGBUS risk is real (project dir OR the conda
# env holding the .so files is on FUSE) AND there is enough memory
# headroom that pinning won't trip the OOM killer.
_on_fuse = (_tofu_path_is_fuse(os.path.dirname(os.path.abspath(__file__)))
or _tofu_path_is_fuse(sys.prefix))
if not _on_fuse:
return False, 'not on FUSE (no SIGBUS risk to mitigate)'
_limit = _tofu_cgroup_mem_limit_bytes()
if _limit is None:
return True, 'on FUSE, cgroup memory unlimited'
try:
_min_gb = float(os.environ.get('TOFU_MLOCK_MIN_LIMIT_GB', '8'))
except ValueError:
_min_gb = 8.0
_gib = float(1 << 30)
if _limit >= _min_gb * _gib:
return True, 'on FUSE, cgroup limit %.1fGiB >= %.1fGiB' % (_limit / _gib, _min_gb)
return False, ('on FUSE but cgroup limit %.1fGiB < %.1fGiB — skipping to avoid '
'OOM (set TOFU_MLOCK=1 to force)' % (_limit / _gib, _min_gb))
_tofu_do_mlock, _tofu_mlock_reason = _tofu_should_mlock()
if _tofu_do_mlock:
try:
import ctypes as _ctypes
_MCL_CURRENT, _MCL_FUTURE = 1, 2
_libc = _ctypes.CDLL('libc.so.6', use_errno=True)
if _libc.mlockall(_MCL_CURRENT | _MCL_FUTURE) != 0:
import errno as _errno
_mlk_err = _ctypes.get_errno()
# ENOMEM (12) = memlock rlimit too low — common in containers
if _mlk_err == _errno.ENOMEM:
os.write(2, b'[boot] mlockall skipped: memlock rlimit too low\n')
else:
os.write(2, (b'[boot] mlockall failed errno=%d\n' % _mlk_err))
else:
os.write(2, b'[boot] mlockall(MCL_CURRENT|MCL_FUTURE) OK '
b'\xe2\x80\x94 pages pinned\n')
except Exception as _mlk_exc:
try:
os.write(2, (b'[boot] mlockall unavailable: %s\n'
% str(_mlk_exc).encode(errors='replace')))
except OSError:
pass
else:
try:
os.write(2, (b'[boot] mlockall skipped \xe2\x80\x94 %s\n'
% _tofu_mlock_reason.encode(errors='replace')))
except OSError:
pass
# ── Record process start time (same as server.py) ──
_PROC_T0 = time.time()
try:
os.write(2, b'\033[36m[boot + 0.0s]\033[0m \xf0\x9f\xab\xa7 Tofu '
b'async bootstrap \xe2\x80\x94 importing core libraries\xe2\x80\xa6\n')
except OSError:
pass
# ── Auto-activate conda env (reuse server.py logic) ──
# This must happen before any third-party imports.
_PROJ_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _PROJ_DIR)
# ── Dev fallback: locate a local tofu-search checkout when it isn't
# pip-installed (production installs it via requirements.txt). Set
# TOFU_SEARCH_PATH to the repo root of a sibling tofu-search clone.
_TOFU_SEARCH_PATH = os.environ.get('TOFU_SEARCH_PATH', '')
if _TOFU_SEARCH_PATH and os.path.isdir(_TOFU_SEARCH_PATH):
sys.path.insert(0, _TOFU_SEARCH_PATH)
def _tofu_maybe_reexec_into_env():
"""Re-exec into Tofu's conda env if not already there."""
marker = os.path.join(_PROJ_DIR, '.tofu_env.json')
if not os.path.isfile(marker):
return
try:
with open(marker, 'r', encoding='utf-8') as f:
cfg = json.load(f)
except Exception:
return
target_py = cfg.get('python') or ''
env_prefix = cfg.get('env_prefix') or ''
backend = cfg.get('backend') or ''
if not target_py or not os.access(target_py, os.X_OK):
return
# Are we ALREADY running inside the target env? Prefer a prefix check over a
# bare interpreter-path comparison: a uv venv's bin/python is a symlink to a
# base CPython, so realpath(target_py) can equal realpath(sys.executable)
# even though we are NOT running with the venv's site-packages active —
# comparing sys.prefix to env_prefix catches that. Fall back to the
# interpreter-path compare when env_prefix is absent.
already_in_env = False
if env_prefix:
try:
already_in_env = (os.path.realpath(sys.prefix) == os.path.realpath(env_prefix))
except OSError:
already_in_env = (sys.prefix == env_prefix)
else:
try:
already_in_env = os.path.realpath(target_py) == os.path.realpath(sys.executable)
except OSError:
already_in_env = (target_py == sys.executable)
if already_in_env:
return
if os.environ.get('_TOFU_ENV_REEXEC') == '1':
return
if env_prefix and os.path.isdir(env_prefix):
env_lib = os.path.join(env_prefix, 'lib')
if os.path.isdir(env_lib):
os.environ['LD_LIBRARY_PATH'] = (
env_lib + os.pathsep + os.environ.get('LD_LIBRARY_PATH', ''))
env_bin = os.path.join(env_prefix, 'bin')
if os.path.isdir(env_bin):
os.environ['PATH'] = env_bin + os.pathsep + os.environ.get('PATH', '')
# Only masquerade as a conda env when we ARE one. A uv venv
# (backend='uv') is not conda; setting CONDA_PREFIX would make
# bootstrap.py's _running_in_conda_env() misfire and route its pip
# fallback down the conda-forge branch.
if backend != 'uv':
os.environ.setdefault('CONDA_PREFIX', env_prefix)
os.environ['_TOFU_ENV_REEXEC'] = '1'
try:
os.execv(target_py, [target_py, *sys.argv])
except OSError:
os.environ.pop('_TOFU_ENV_REEXEC', None)
_tofu_maybe_reexec_into_env()
# ── .env loading ──
def _load_dotenv():
env_path = os.path.join(_PROJ_DIR, '.env')
if not os.path.exists(env_path):
return
with open(env_path) as f:
for line in f:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, _, value = line.partition('=')
key, value = key.strip(), value.strip()
if key not in os.environ:
os.environ[key] = value
_load_dotenv()
# ═══════════════════════════════════════════════════════════════════════
# Sync→loop body-read bounded wait (extracted for testability)
# ═══════════════════════════════════════════════════════════════════════
# ``_run_coro_sync`` (installed by the Flask→Quart shim below) bridges a sync
# route handler running in an executor thread to the MAIN event loop to read
# the request body (get_json / form / files / data). If the loop is EVER wedged
# (a blocking call slipped onto it, a FUSE/PG stall), an UNBOUNDED
# ``future.result()`` there blocks the worker thread FOREVER; every subsequent
# request-body read queues behind it and the whole sync-executor pool is
# exhausted — the "whole site frozen, must restart" failure mode. Bounding the
# wait severs that one failure mode WITHOUT hurting legitimate slow large
# uploads. These two helpers are module-level (not closure-local) so a unit test
# can exercise the bound directly, mirroring the ``timeout=30`` contract the
# sibling ``_sync_safe`` wrapper already carries.
def _resolve_sync_body_timeout():
"""Seconds to wait for a cross-thread request-body read before aborting.
Reads ``TOFU_SYNC_BODY_TIMEOUT`` (default 300s — generous so a genuine slow
upload is never cut short; this is a backstop against an infinitely wedged
loop, NOT a tight per-request budget). A value ``<= 0`` opts out (unbounded,
the legacy behaviour) and returns ``None``.
"""
raw = os.environ.get('TOFU_SYNC_BODY_TIMEOUT', '') or '300'
try:
val = float(raw)
except (ValueError, TypeError) as e:
logging.getLogger('server').debug(
'[Server] bad TOFU_SYNC_BODY_TIMEOUT=%r, using 300s: %s', raw, e)
return 300.0
return None if val <= 0 else val
def _await_coro_on_loop(coro, main_loop, timeout):
"""Run ``coro`` on ``main_loop`` from a sync thread, bounded by ``timeout``.
On timeout the coroutine is best-effort cancelled, an ERROR is logged (per
CLAUDE.md §2.2), and ``concurrent.futures.TimeoutError`` propagates so the
handler fails fast instead of hanging the worker thread indefinitely.
"""
from concurrent.futures import TimeoutError as _FuturesTimeoutError
future = asyncio.run_coroutine_threadsafe(coro, main_loop)
try:
return future.result(timeout=timeout)
except _FuturesTimeoutError:
future.cancel()
logging.getLogger('server').error(
'[Server] _run_coro_sync timed out after %ss waiting on the main '
'event loop for a request-body read — the loop is likely wedged. '
'Aborting this read instead of hanging the worker thread (raise '
'TOFU_SYNC_BODY_TIMEOUT if this is a genuine slow upload).', timeout)
raise
# ═══════════════════════════════════════════════════════════════════════
# Framework Compatibility Shim
# ═══════════════════════════════════════════════════════════════════════
# Quart is API-compatible with Flask but lives under `quart.*` imports.
# Our routes and lib/ code import from flask. We install a shim so that
# `from flask import *` resolves to Quart's equivalents at runtime.
# This is the official Quart migration approach.
def _install_flask_shim():
"""Make `from flask import X` resolve to Quart equivalents.
Quart is a superset of Flask's API. This shim allows all existing
route code to work without changing any import statements.
Key difference: Quart makes send_from_directory, send_file, and
make_response async. When sync route handlers (running in Quart's
thread pool) call these, they get coroutine objects. We wrap them
with sync-safe versions that detect this and await appropriately.
"""
try:
import quart
except ImportError:
sys.stderr.write(
'\033[31m[server.py] ERROR: quart is not installed.\n'
' Install with: pip install quart hypercorn cryptography\033[0m\n')
sys.exit(1)
import asyncio
import functools
import inspect
# Recover the GENUINE async helpers. If server.py is imported/exec'd
# more than once in the same process (e.g. a test re-imports it via
# importlib), ``quart.make_response`` etc. are already our sync-safe
# wrappers from the first install. Capturing those as the "originals"
# and wrapping them again would corrupt ``_orig_make_response_async``
# (it would point at a sync-safe wrapper instead of the real async
# ``quart.make_response``), so error handlers that
# ``await _orig_make_response_async(...)`` would route through the
# thread-bridge and deadlock. ``_sync_safe`` stashes the genuine async
# function on ``.__wrapped__``; unwrap through it so a re-install
# always starts from the real async helpers.
def _genuine(fn):
while getattr(fn, '_quart_async_wrapper', False):
fn = getattr(fn, '__wrapped__', fn)
return fn
_orig_send_from_directory = _genuine(quart.send_from_directory)
_orig_send_file = _genuine(quart.send_file)
_orig_make_response = _genuine(quart.make_response)
def _sync_safe(async_fn):
"""Wrap an async function to be callable from sync code in a thread."""
@functools.wraps(async_fn)
def wrapper(*args, **kwargs):
coro = async_fn(*args, **kwargs)
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop and loop.is_running():
# We're in a thread with an event loop running elsewhere.
# Use the Quart-provided mechanism to run coroutines from
# sync code within a request context.
future = asyncio.run_coroutine_threadsafe(coro, loop)
return future.result(timeout=30)
else:
return asyncio.run(coro)
# Also make it awaitable for async callers
wrapper._async = async_fn
wrapper.__wrapped__ = async_fn
# Mark it so Quart's ensure_async can detect the dual nature
wrapper._quart_async_wrapper = True
return wrapper
# Quart 0.19.x's send_file / send_from_directory still use the
# pre-Flask-2.0 kwarg name `attachment_filename`; modern route code
# uses Flask's `download_name`. Normalize so callers can use the
# current Flask spelling regardless of the installed Quart version.
def _compat_download_name(async_fn):
@functools.wraps(async_fn)
def adapter(*args, **kwargs):
if 'download_name' in kwargs:
params = inspect.signature(async_fn).parameters
if 'download_name' not in params and 'attachment_filename' in params:
kwargs['attachment_filename'] = kwargs.pop('download_name')
return async_fn(*args, **kwargs)
# Mark so _genuine() unwraps through this adapter on re-install,
# recovering the real async helper rather than stopping here.
adapter.__wrapped__ = async_fn
adapter._quart_async_wrapper = True
return adapter
# Replace in quart module so `from flask import send_from_directory`
# gets the sync-safe version
quart.send_from_directory = _sync_safe(_compat_download_name(_orig_send_from_directory))
quart.send_file = _sync_safe(_compat_download_name(_orig_send_file))
quart.make_response = _sync_safe(_orig_make_response)
# Expose originals at module level for async code that needs to await directly
global _orig_make_response_async
_orig_make_response_async = _orig_make_response
# ── Patch Request async methods/properties for sync route handlers ──
# In Quart, get_json(), form, files, data, and json are async. Sync
# route handlers (run in executor threads via run_sync) get coroutine
# objects instead of values. Monkey-patch the Request class to run
# the coroutine on the MAIN event loop — NOT a fresh child loop.
#
# The naive ``asyncio.run(coro)`` here is wrong: it spins up a new
# loop in the worker thread, and the coroutine then awaits hypercorn's
# request body Future, which lives on the main loop. Cross-loop
# awaits never wake up — symptom: large POST bodies hang server-side
# until the client times out, while small bodies (already inlined
# into the ASGI scope before dispatch) work fine. Fix: schedule via
# ``run_coroutine_threadsafe`` on the loop saved by
# ``hub.set_loop`` at startup.
from quart.wrappers import Request as _QuartRequest
_orig_get_json = _QuartRequest.get_json
def _run_coro_sync(coro):
"""Run a coroutine from a sync context (executor thread).
The cross-thread wait is bounded by ``TOFU_SYNC_BODY_TIMEOUT`` (default
300s, see :func:`_resolve_sync_body_timeout`) so a wedged event loop can
never hang a worker thread forever and exhaust the sync-executor pool.
On timeout the coroutine is cancelled and
``concurrent.futures.TimeoutError`` propagates instead of blocking
indefinitely. Delegates to the module-level :func:`_await_coro_on_loop`
so the bound is unit-testable.
"""
if not inspect.iscoroutine(coro):
return coro
try:
from lib.push import hub as _push_hub
main_loop = getattr(_push_hub, '_loop', None)
except Exception:
main_loop = None
if main_loop is not None and main_loop.is_running():
return _await_coro_on_loop(
coro, main_loop, _resolve_sync_body_timeout())
return asyncio.run(coro)
def _sync_safe_get_json(self, *args, **kwargs):
return _run_coro_sync(_orig_get_json(self, *args, **kwargs))
# Stash the genuine async original ON the wrapper so async handlers can
# recover it regardless of how many times the shim is (re)installed or
# which module object holds it (test harnesses sometimes exec server.py as
# a second module). Always unwrap to the FIRST genuine coroutine fn.
_genuine_get_json = getattr(_orig_get_json, '_genuine_async_get_json', _orig_get_json)
_sync_safe_get_json._genuine_async_get_json = _genuine_get_json
_QuartRequest.get_json = _sync_safe_get_json
# Patch async properties: form, files, data, json
_orig_form_prop = _QuartRequest.form
_orig_files_prop = _QuartRequest.files
_orig_data_prop = _QuartRequest.data
def _make_sync_safe_property(orig_prop):
_fget = orig_prop.fget
@property
def _prop(self):
return _run_coro_sync(_fget(self))
return _prop
_QuartRequest.form = _make_sync_safe_property(_orig_form_prop)
_QuartRequest.files = _make_sync_safe_property(_orig_files_prop)
_QuartRequest.data = _make_sync_safe_property(_orig_data_prop)
# json property delegates to the already-patched sync get_json
@property
def _json_prop(self):
return self.get_json()
_QuartRequest.json = _json_prop
# Install the shim: make `import flask` resolve to quart
sys.modules['flask'] = quart
# Also shim sub-modules that code might import from
for attr in ('json', 'globals', 'helpers', 'wrappers', 'ctx'):
quart_sub = f'quart.{attr}'
flask_sub = f'flask.{attr}'
if quart_sub in sys.modules:
sys.modules[flask_sub] = sys.modules[quart_sub]
# Werkzeug exceptions are used directly in some places
# Quart re-exports them, but ensure werkzeug is still importable
import importlib.util
if importlib.util.find_spec('werkzeug') is None:
logging.getLogger(__name__).debug('werkzeug not importable; relying on quart re-exports')
_install_flask_shim()
# ── Now safe to import Quart (which the routes will see as 'flask') ──
import quart # noqa: F401 — kept so quart.* monkeypatches in _install_flask_shim resolve
from quart import Quart, redirect, request
# ═══════════════════════════════════════════════════════════════════════
# Logging (reuse server.py's architecture)
# ═══════════════════════════════════════════════════════════════════════
import mimetypes
mimetypes.init()
mimetypes.add_type('text/javascript', '.js')
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('application/json', '.json')
mimetypes.add_type('image/svg+xml', '.svg')
mimetypes.add_type('font/woff2', '.woff2')
mimetypes.add_type('font/ttf', '.ttf')
mimetypes.add_type('application/wasm', '.wasm')
BASE_DIR = _PROJ_DIR
# ── Logging setup (identical to server.py) ──
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
# LOG_DIR must be WRITABLE. In a frozen desktop build BASE_DIR is the read-only
# bundle root, so route logs to the writable root (see lib/runtime_paths).
from lib.runtime_paths import data_root as _tofu_data_root, logs_root as _tofu_logs_root
LOG_DIR = _tofu_logs_root()
os.makedirs(LOG_DIR, exist_ok=True)
_LOG_FMT = '%(asctime)s [%(levelname)s] %(name)s [%(threadName)s]: %(message)s'
_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
_formatter = logging.Formatter(_LOG_FMT, datefmt=_LOG_DATEFMT)
# 'tofu_search' is the extracted search/fetch library (sibling package). Its