-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathserver.py
More file actions
2725 lines (2416 loc) · 117 KB
/
Copy pathserver.py
File metadata and controls
2725 lines (2416 loc) · 117 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 (ASGI).
App entry point. Uses:
- Quart (async Flask from Pallets) as the application framework
- Hypercorn as the ASGI server with HTTP/2 support
- Optional TLS/HTTP2 for explicitly configured direct deployments
All existing Flask-style sync route handlers run unchanged in a thread pool.
Usage:
python server.py # HTTP/1.1 (proxy-safe default)
TOFU_TLS=1 python server.py # HTTPS + HTTP/2 (auto-cert)
python server.py --no-tls # Explicit HTTP/1.1
python server.py --certfile cert.pem --keyfile key.pem # custom cert
"""
import asyncio
import os
import sys
import json
import logging
import time
import threading
import faulthandler
def _delegate_executable_to_manager():
"""Fast-path a human ``python server.py`` into the sole lifecycle owner."""
external_owner = (
os.environ.get('TOFU_SERVER_WORKER') == '1'
or os.environ.get('_TOFU_VIA_BOOTSTRAP') == '1'
or os.environ.get('TOFU_RUN_SERVER') == '1'
# In-place update/HEAD re-exec keeps the original worker PID and sets
# this port handoff marker before execv. It is already the worker; a
# manager handoff here would strand that PID holding the instance lock
# while it waits for itself to become ready.
or bool(os.environ.get('_TOFU_REEXEC_PORT'))
or os.getpid() == 1 # Docker/container entrypoint owns this process
)
if __name__ != '__main__' or external_owner:
return
if any(arg in ('-h', '--help') for arg in sys.argv[1:]):
sys.stdout.write(
'usage: python server.py [--host HOST] [--port PORT] [--no-tls] '
'[--certfile FILE --keyfile FILE]\n\n'
'Starts Tofu through the project-local manager. Operations: '
'python serverctl.py {status,stop,restart,logs,doctor}\n')
raise SystemExit(0)
# Preserve the established environment-selection contract without loading
# the application first. The re-executed wrapper will immediately hand off
# to serverctl; the eventual worker still runs the full native-path setup.
project = os.path.dirname(os.path.abspath(__file__))
marker = os.path.join(project, '.tofu_env.json')
try:
with open(marker, encoding='utf-8') as fh:
cfg = json.load(fh)
target = cfg.get('python') or ''
prefix = cfg.get('env_prefix') or ''
in_target = (
os.path.realpath(sys.prefix) == os.path.realpath(prefix)
if prefix else os.path.realpath(sys.executable) == os.path.realpath(target)
)
if target and os.access(target, os.X_OK) and not in_target \
and os.environ.get('_TOFU_ENV_REEXEC') != '1':
os.environ['_TOFU_ENV_REEXEC'] = '1'
os.execv(target, [target, *sys.argv])
except (OSError, ValueError, TypeError):
pass
try:
from serverctl import managed_start
code = managed_start(sys.argv[1:], wait=180.0, source='python-server.py')
except Exception as exc:
sys.stderr.write(
'[server.py] Could not hand startup to the Tofu manager: %s\n'
'Diagnose with: %s serverctl.py doctor\n' % (exc, sys.executable))
code = 1
raise SystemExit(code)
_delegate_executable_to_manager()
def _install_numeric_thread_defaults() -> int:
"""Bound implicit BLAS/OpenMP pools before NumPy or ML imports.
High-core personal hosts otherwise make OpenBLAS eagerly retain one native
worker per visible CPU (64 in the measured deployment) even while Tofu is
idle. Tofu already owns request, DB, agent, and tool executors; an
additional host-sized pool per numeric runtime causes oversubscription and
needless thread stacks under memory pressure. Explicit library variables
always win. ``TOFU_NUMERIC_THREADS`` changes only the zero-config default.
"""
raw = os.environ.get('TOFU_NUMERIC_THREADS', '4')
try:
workers = int(raw or '4')
except (TypeError, ValueError):
workers = 4
workers = max(1, min(32, workers))
value = str(workers)
for name in ('OPENBLAS_NUM_THREADS', 'OMP_NUM_THREADS',
'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'):
os.environ.setdefault(name, value)
return workers
# Must run before the first ``lib`` import: route/plugin discovery eventually
# imports NumPy, at which point OpenBLAS has already fixed its native pool.
_NUMERIC_THREADS = _install_numeric_thread_defaults()
# Internal process marker (NOT a user knob — the owner directive 2026-08-05:
# plain `python server.py` carries everything). lib.database's local-primary
# migration gates on this: only the server's own boot may stop/start clusters
# and flip the primary. A side process that merely imports lib.database (agent
# probes, tooling) must never fire it — measured 2026-08-05: two bare imports
# each burned a full 46 GB dump+restore attempt. Must precede lib imports.
os.environ.setdefault('TOFU_SERVER_PROCESS', '1')
# ── 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 a per-process FUSE-backed file (durable
# across box restarts) and a per-process tmpfs mirror (immune to FUSE stalls).
# Only a real ``python server.py`` process arms the sinks. Historically this
# ran on every ``import server`` and appended to one shared file: test/tool
# imports alone produced 44k headers, while 1,598 stall dumps grew it to
# 125 MiB with no bound.
_fault_log = None
_fault_shm_log = None
_FAULT_LOG_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'logs')
_FAULT_LOG_PATH = os.path.join(
_FAULT_LOG_DIR, 'tofu_faulthandler_%d.log' % os.getpid())
_FAULT_SHM_PATH = '/dev/shm/tofu_faulthandler_%d.log' % os.getpid()
def _arm_faulthandler_sinks():
"""Open early crash sinks for the executable server, never an importer."""
global _fault_log, _fault_shm_log, _FAULT_LOG_DIR, _FAULT_LOG_PATH
header = '=== faulthandler armed pid=%d at %s ===\n' % (
os.getpid(), time.strftime('%Y-%m-%d %H:%M:%S'))
# Arm tmpfs first, before importing even the lightweight writable-path
# resolver. This preserves early native-crash capture while ensuring a
# fresh/XDG or frozen install places its durable file beside all other logs
# instead of writing into a source/read-only bundle.
try:
_fault_shm_log = open(_FAULT_SHM_PATH, 'w+', buffering=1)
_fault_shm_log.write(header)
faulthandler.enable(file=_fault_shm_log, all_threads=True)
except (OSError, RuntimeError):
if _fault_shm_log is not None:
try:
_fault_shm_log.close()
except OSError:
pass
_fault_shm_log = None
try:
from lib.log import LOG_DIR as _writable_log_dir
_FAULT_LOG_DIR = _writable_log_dir
_FAULT_LOG_PATH = os.path.join(
_FAULT_LOG_DIR, 'tofu_faulthandler_%d.log' % os.getpid())
except Exception:
pass
try:
os.makedirs(_FAULT_LOG_DIR, exist_ok=True)
_fault_log = open(_FAULT_LOG_PATH, 'w+', buffering=1)
_fault_log.write(header)
except OSError:
_fault_log = None
# Fall back to the durable fd, then stderr, when tmpfs is unavailable.
# ``w+`` lets the healthy heartbeat cap repeated non-fatal stall dumps
# without replacing the descriptor retained by faulthandler.
if _fault_shm_log is None:
if _fault_log is not None:
faulthandler.enable(file=_fault_log, all_threads=True)
else:
faulthandler.enable(all_threads=True)
if __name__ == '__main__':
_arm_faulthandler_sinks()
# ── 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, *, phase='serving'):
"""Atomically stamp ``{pid, ts}`` (wall-clock) into the sidecar.
``phase='booting'`` is stamped by the executable immediately after taking
the instance lock, before importing the database or starting background
writers. A contender gives that phase a longer grace period than a stale
serving-loop heartbeat, so a legitimate schema migration cannot be
mistaken for a wedged server. Best-effort: a write failure NEVER raises.
Atomic (temp + ``os.replace``) means 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, 'phase': phase}))
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 _read_heartbeat_state(path=None):
"""Return the heartbeat record while keeping ``_read_heartbeat`` stable.
Old sidecars without ``phase`` are serving heartbeats. Invalid records are
ambiguous and therefore return ``None`` (the reclaim path fails safe).
"""
path = path or _heartbeat_path()
try:
with open(path) as f:
data = json.loads(f.read() or '{}')
pid = int(data['pid'])
ts = float(data['ts'])
phase = str(data.get('phase') or 'serving')
if phase not in ('booting', 'serving'):
return None
return {'pid': pid, 'ts': ts, 'phase': phase}
except (OSError, KeyError, ValueError, TypeError):
return 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 _boot_heartbeat_stale_threshold():
"""Grace for a lock holder that has not reached the serving loop yet.
Production startup can legitimately spend tens of seconds migrating and
verifying a 20 GB SQLite authority. Keep the bound finite so a process
genuinely wedged during import remains reclaimable without weakening the
normal 30-second serving-loop detector.
"""
try:
value = float(os.environ.get('TOFU_BOOT_HEARTBEAT_GRACE_SECS', '') or '180')
except (ValueError, TypeError):
value = 180.0
return max(60.0, min(900.0, value))
_SERVE_MODE_FILE = '.last_serve_mode'
def _serve_mode_path():
"""Absolute path of the serve-mode sidecar (data/.last_serve_mode)."""
return os.path.join(_tofu_data_root(), _SERVE_MODE_FILE)
def _record_serve_mode(mode, path=None):
"""Persist the protocol we are ACTUALLY serving ('http'|'https') so the
watchdog (deploy/tofu_guard.sh) can (a) probe /api/health with the right
scheme and (b) replay the same TLS decision on auto-relaunch — a
cron-env relaunch re-runs _detect_reverse_proxy blind and came up TLS
behind a plain-HTTP proxy (the 2026-08-03 'socket hang up' incident).
Best-effort: a write failure must never block startup."""
if mode not in ('http', 'https'):
raise ValueError('serve mode must be http|https, got %r' % (mode,))
path = path or _serve_mode_path()
try:
from lib.json_store import write_text_atomic
write_text_atomic(path, mode + '\n')
except Exception as e:
logging.getLogger('server').warning(
'[TLS] could not record serve mode to %s: %s', path, e)
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.
"""
state = _read_heartbeat_state(path)
if state is None or state['pid'] != pid:
return None
now = time.time() if now is None else now
age = now - state['ts']
threshold = (_boot_heartbeat_stale_threshold()
if state['phase'] == 'booting'
else _heartbeat_stale_threshold())
if age < 0 or age <= 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,
*, mark_booting=False):
"""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,
mark_booting=mark_booting)
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)
if mark_booting:
_write_heartbeat(pid=os.getpid(), phase='booting')
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 _fault_dump_limits():
"""Return bounded per-file and stale-dump retention settings."""
def _integer(name, default, minimum, maximum):
try:
value = int(os.environ.get(name, '') or default)
except (TypeError, ValueError):
value = default
return max(minimum, min(maximum, value))
return {
'active_bytes': _integer(
'TOFU_FAULT_DUMP_MAX_BYTES', 16 * 1024 * 1024,
1 * 1024 * 1024, 256 * 1024 * 1024),
'stale_files': _integer(
'TOFU_FAULT_DUMP_FILES', 8, 1, 64),
'stale_bytes': _integer(
'TOFU_FAULT_DUMP_TOTAL_BYTES', 64 * 1024 * 1024,
4 * 1024 * 1024, 1024 * 1024 * 1024),
}
def _trim_fault_sink_if_oversize(sink, max_bytes, *, header=''):
"""Reuse a live fd while bounding repeated recoverable stall dumps.
Replacing the path is unsafe because the C-level faulthandler retains the
old descriptor. Truncating only after its one-shot timer is cancelled
preserves descriptor identity and keeps the next capture on the named
file. Returns True when a trim occurred.
"""
if sink is None or max_bytes <= 0:
return False
try:
sink.flush()
if os.fstat(sink.fileno()).st_size <= max_bytes:
return False
sink.seek(0)
sink.truncate(0)
if header:
sink.write(header)
sink.flush()
return True
except (OSError, ValueError):
return False
def _reset_fault_sink(sink, *, header=''):
"""Keep only the newest manual durable dump on a live sink fd."""
if sink is None:
return False
try:
sink.flush()
sink.seek(0)
sink.truncate(0)
if header:
sink.write(header)
sink.flush()
return True
except (OSError, ValueError):
return False
def _prune_fault_dump_budget(directory, *, keep_basename='', pid_alive=_pid_alive,
max_dead_files=8, max_dead_bytes=64 * 1024 * 1024):
"""Keep newest dead-process evidence within count and byte budgets.
Live process files, the current sink and unrelated files are never
touched. Unlike the historical prune-all helper, retaining the newest
dead files means the next boot does not erase the crash it is meant to
diagnose. Returns the number of old dead dumps removed.
"""
import glob as _glob
pattern = os.path.join(
directory, _FAULT_DUMP_PREFIX + '*' + _FAULT_DUMP_SUFFIX)
dead = []
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:
stat = os.stat(path)
except OSError:
continue
dead.append((stat.st_mtime_ns, base, path, stat.st_size))
removed = 0
kept_files = 0
kept_bytes = 0
for _mtime, _base, path, size in sorted(dead, reverse=True):
fits = (kept_files < max(0, int(max_dead_files))
and kept_bytes + size <= max(0, int(max_dead_bytes)))
if fits:
kept_files += 1
kept_bytes += size
continue
try:
os.unlink(path)
removed += 1
except OSError:
pass
return removed
from lib.server_runtime_probes import stall_pressure_context
def _stall_pressure_context():
"""Compatibility hook consumed by the extracted loop watchdog owner."""
return stall_pressure_context()
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 _port_bound(port, host='127.0.0.1', timeout=0.5):
"""True iff a TCP connection to host:port succeeds (listener present).
Scheme-agnostic: works for TLS and plain-HTTP listeners alike."""
import socket as _s
try:
with _s.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def _listener_death_decide(was_bound, bound, misses, k):
"""Pure decision for the serve-listener watch (second layer after the
loop heartbeat). Returns ``(was_bound, misses, should_exit)``.
Arms only after the listener was seen bound at least once (the pre-serve
startup window is not our watch); counts CONSECUTIVE misses from there;
a single recovery resets the streak. The serve task dying while the
loop stays alive (the 2026-08-03 11:14 state: no listener, live lock,
FRESH heartbeat) is invisible to every external probe — the watchdog
sees a live pid and yields forever — so the process must die loudly
itself and hand the watchdog a clean, handleable death."""
if bound:
return (True, 0, False)
if not was_bound:
return (False, 0, False)
misses += 1
return (True, misses, misses >= k)
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: retain recent dead-process evidence but bound both the
# tmpfs and durable per-pid families. The file opened for this process and any
# other genuinely live server are always preserved.
if _fault_shm_log is not None:
try:
_fault_limits = _fault_dump_limits()
_pruned = _prune_fault_dump_budget(
directory='/dev/shm',
keep_basename=os.path.basename(_FAULT_SHM_PATH),
max_dead_files=_fault_limits['stale_files'],
max_dead_bytes=_fault_limits['stale_bytes'])
if _pruned:
sys.stderr.write('[boot] pruned %d over-budget faulthandler dump(s) from /dev/shm\n'
% _pruned)
except Exception:
pass # cleanup is best-effort; never block boot on it
if _fault_log is not None:
try:
_fault_limits = _fault_dump_limits()
_pruned = _prune_fault_dump_budget(
directory=_FAULT_LOG_DIR,
keep_basename=os.path.basename(_FAULT_LOG_PATH),
max_dead_files=_fault_limits['stale_files'],
max_dead_bytes=_fault_limits['stale_bytes'])
if _pruned:
sys.stderr.write('[boot] pruned %d over-budget durable fault dump(s)\n'
% _pruned)
except Exception:
pass
# ── 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 the
# limit AND live usage: on a SHARED cgroup the ceiling can be the whole
# machine yet already ~full, and pinning there both adds unreclaimable pages
# and inflates our oom_score so the killer targets us first — so we also skip
# when the cgroup is already past TOFU_MLOCK_MAX_USAGE_PCT (default 85%) full.
# Override: TOFU_MLOCK=1 forces it on, =auto enables the legacy headroom-gated
# mode. The production default is OFF: MCL_FUTURE locks every later mmap and
# allocation, so a healthy-looking boot can grow into tens of GiB of
# unreclaimable memory hours later. A one-shot startup headroom check cannot
# make that safe. Operators with a proven FUSE SIGBUS workload can still opt
# into the bounded-by-cgroup legacy policy explicitly with TOFU_MLOCK=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_cgroup_mem_usage_bytes():
"""Current cgroup memory usage in bytes, or None if unknown (stdlib-only).
Includes reclaimable page cache on purpose: a shared cgroup running at the
cache edge is exactly the contended, spike-prone state where adding
unreclaimable pinned pages is net-harmful (see _tofu_should_mlock).
"""
for _p in ('/sys/fs/cgroup/memory.current', # cgroup v2
'/sys/fs/cgroup/memory/memory.usage_in_bytes'): # cgroup v1
try:
with open(_p, 'r') as _f:
_raw = _f.read().strip()
except OSError:
continue
try:
_val = int(_raw)
except ValueError:
continue
if _val < 0:
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', 'off').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 False, ('on FUSE but cgroup limit %.1fGiB < %.1fGiB — skipping to avoid '
'OOM (set TOFU_MLOCK=1 to force)' % (_limit / _gib, _min_gb))
# The cgroup limit is generous, but on a SHARED cgroup that ceiling can be
# the whole machine and already ~full of siblings + FUSE page/slab cache.
# Pinning here adds unreclaimable pages AND inflates our own oom_score, so
# the OOM killer picks us first (highest-RSS process in the group). Gate on
# LIVE headroom: skip if usage already sits above TOFU_MLOCK_MAX_USAGE_PCT
# (default 85%) of the limit. Unknown usage → proceed (matches prior behaviour).
_usage = _tofu_cgroup_mem_usage_bytes()
if _usage is not None and _usage > 0:
try:
_max_pct = float(os.environ.get('TOFU_MLOCK_MAX_USAGE_PCT', '85'))
except ValueError:
_max_pct = 85.0
_used_pct = 100.0 * _usage / float(_limit)
if _used_pct >= _max_pct:
return False, ('on FUSE but cgroup %.1f%% full (%.1f/%.1fGiB) >= %.0f%% — '
'skipping to avoid OOM on a contended shared cgroup '
'(set TOFU_MLOCK=1 to force)'
% (_used_pct, _usage / _gib, _limit / _gib, _max_pct))
return True, ('on FUSE, cgroup limit %.1fGiB >= %.1fGiB and %.1f%% used < %.0f%%'
% (_limit / _gib, _min_gb, _used_pct, _max_pct))
return True, 'on FUSE, cgroup limit %.1fGiB >= %.1fGiB (usage unknown)' % (_limit / _gib, _min_gb)
_tofu_do_mlock, _tofu_mlock_reason = _tofu_should_mlock()
if _tofu_do_mlock:
try:
import ctypes as _ctypes