-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathserver_manager.py
More file actions
2518 lines (2370 loc) · 104 KB
/
Copy pathserver_manager.py
File metadata and controls
2518 lines (2370 loc) · 104 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
"""Single-owner lifecycle state machine for the Tofu server worker.
This module intentionally uses only the Python standard library. The manager
must remain observable and able to stop/recover the worker even when the
application dependency graph or database cannot be imported.
"""
from __future__ import annotations
import json
import logging
import math
import os
import shlex
import signal
import socket
import ssl
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
from runtime_guards import (
RESOURCE_BUDGET_AUTOMATIC_ENV,
RESOURCE_BUDGET_ENV_KEYS,
RESOURCE_BUDGET_POLICY_ENV,
RESOURCE_BUDGET_POLICY_VERSION,
_persistent_data_path,
deployment_resource_default,
install_process_resource_defaults,
)
STATE_VERSION = 1
DEFAULT_SERVER_PORT = 15000
DEFAULT_MONITOR_INTERVAL = 5.0
DEFAULT_BOOT_GRACE = 180.0
DEFAULT_WEDGE_STALE = 180.0
DEFAULT_WEDGE_STREAK = 120.0
DEFAULT_MAX_FAILURES = 5
DEFAULT_FAILURE_WINDOW = 120.0
DEFAULT_FAILURE_HISTORY_KEEP = 50
DEFAULT_WORKER_RSS_CGROUP_FRACTION = 0.70
DEFAULT_SIDECAR_LEASE_RELEASE_WAIT = 10.0
DEFAULT_STORAGE_LEASE_POLL_INTERVAL = 0.1
DEFAULT_FRONTEND_PREFLIGHT_TIMEOUT = 660.0
DEFAULT_EXIT_INTENT_WINDOW = 120.0
CLEAN_WORKER_EXIT_REASONS = frozenset(
{'manual', 'signal', 'restart', 'memory_recycle'})
MIB = 1024 * 1024
WORKER_BUDGET_STATUS_KEYS = (
'TOFU_MAX_INFLIGHT_TASKS',
'TOFU_AGENT_WORKERS',
'TOFU_TASK_RSS_RESERVE_MB',
'TOFU_PROCESS_RSS_RELIEF_MB',
'TOFU_PROCESS_RSS_RECYCLE_MB',
)
CGROUP_OOM_EVENT_PATHS = (
'/sys/fs/cgroup/memory.events',
'/sys/fs/cgroup/memory/memory.oom_control',
)
CGROUP_MEMORY_LIMIT_PATHS = (
'/sys/fs/cgroup/memory.max',
'/sys/fs/cgroup/memory/memory.limit_in_bytes',
)
SERVER_ENV_KEYS = frozenset({
'PORT', 'BIND_HOST', 'TOFU_TLS', 'TLS_CERTFILE', 'TLS_KEYFILE',
'TOFU_DEPLOYMENT_MODE',
'TOFU_DATA_DIR', 'TOFU_DATA_LAYOUT',
'XDG_DATA_HOME', 'LOCALAPPDATA',
'TOFU_SERVER_PYTHON_CACHE', 'TOFU_SERVER_PYTHON_CACHE_DIR',
# Agent scheduling is created before request handling starts. Preserve
# explicit project overrides across manager-owned worker generations.
'TOFU_AGENT_QUEUE_CAPACITY', 'TOFU_AGENT_STUCK_REPLACEMENTS',
# These must exist before the Python worker starts. Loading them later in
# server.py's dotenv phase cannot reconfigure glibc or already-imported
# BLAS/OpenMP runtimes.
'TOFU_MALLOC_ARENA_MAX', 'TOFU_NUMERIC_THREADS',
'OPENBLAS_NUM_THREADS', 'OMP_NUM_THREADS', 'MKL_NUM_THREADS',
'NUMEXPR_NUM_THREADS',
}) | RESOURCE_BUDGET_ENV_KEYS
_DATA_LOCATION_ENV_KEYS = (
'TOFU_DATA_DIR',
'XDG_DATA_HOME',
'LOCALAPPDATA',
)
_PYTEST_CONTEXT_ENV_KEYS = (
'PYTEST_CURRENT_TEST',
'TOFU_PYTEST_RUN_ROOT',
)
logger = logging.getLogger(__name__)
def _now() -> float:
return time.time()
def _hostname() -> str:
try:
return socket.gethostname()
except Exception:
return ''
def cgroup_oom_kill_count() -> int | None:
"""Read the shared cgroup's cumulative OOM-kill counter, if exposed."""
for path in CGROUP_OOM_EVENT_PATHS:
try:
lines = Path(path).read_text(encoding='utf-8').splitlines()
except OSError:
continue
for line in lines:
fields = line.split()
if len(fields) >= 2 and fields[0] == 'oom_kill':
try:
return int(fields[1])
except ValueError:
break
return None
def cgroup_memory_limit_bytes() -> int | None:
"""Return the effective cgroup memory ceiling when it is finite."""
for path in CGROUP_MEMORY_LIMIT_PATHS:
try:
raw = Path(path).read_text(encoding='utf-8').strip()
except OSError:
continue
if not raw or raw == 'max':
continue
try:
value = int(raw)
except ValueError:
continue
# cgroup v1 uses a huge page-aligned sentinel for "unlimited".
if 0 < value < (1 << 60):
return value
return None
def proc_rss_bytes(pid: int) -> int | None:
"""Read one process's resident set without importing application code."""
try:
fields = Path(f'/proc/{int(pid)}/statm').read_text(
encoding='utf-8').split()
return int(fields[1]) * int(os.sysconf('SC_PAGE_SIZE'))
except (OSError, ValueError, IndexError, TypeError):
return None
def worker_rss_recycle_limit_bytes(
raw_mb: str | None = None,
*,
environment: dict[str, str] | None = None,
) -> int:
"""Resolve the manager's external worker RSS ceiling; zero disables it."""
if raw_mb not in (None, ''):
try:
configured_mb = float(raw_mb)
if configured_mb == 0:
return 0
if configured_mb > 0:
return max(1, int(configured_mb * MIB))
raise ValueError('must be non-negative')
except (TypeError, ValueError):
logger.warning(
'invalid TOFU_PROCESS_RSS_RECYCLE_MB=%r; using adaptive default',
raw_mb)
default = int(deployment_resource_default(
'TOFU_PROCESS_RSS_RECYCLE_MB', environment) * MIB)
cgroup_limit = cgroup_memory_limit_bytes()
if cgroup_limit is not None:
default = min(
default, int(cgroup_limit * DEFAULT_WORKER_RSS_CGROUP_FRACTION))
return max(1, default)
def _atomic_json(path: Path, value: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f'{path.name}.{os.getpid()}.tmp')
with tmp.open('w', encoding='utf-8') as fh:
json.dump(value, fh, ensure_ascii=False, indent=2, sort_keys=True)
fh.write('\n')
fh.flush()
os.fsync(fh.fileno())
os.replace(tmp, path)
def _read_json(path: Path) -> dict[str, Any]:
try:
with path.open(encoding='utf-8') as fh:
value = json.load(fh)
return value if isinstance(value, dict) else {}
except (OSError, ValueError, TypeError):
return {}
def proc_start_ticks(pid: int) -> int | None:
"""Return Linux /proc start ticks, which disambiguate PID reuse."""
try:
raw = Path(f'/proc/{int(pid)}/stat').read_text(encoding='utf-8')
# comm is parenthesized and may contain spaces; fields after its final
# ')' begin with field 3. starttime is field 22 => remainder index 19.
rest = raw[raw.rfind(')') + 2:].split()
return int(rest[19])
except (OSError, ValueError, IndexError, TypeError):
return None
def proc_start_epoch(pid: int) -> float | None:
ticks = proc_start_ticks(pid)
if ticks is None:
return None
try:
boot = None
for line in Path('/proc/stat').read_text(encoding='utf-8').splitlines():
if line.startswith('btime '):
boot = float(line.split()[1])
break
if boot is None:
return None
return boot + (ticks / float(os.sysconf('SC_CLK_TCK')))
except (OSError, ValueError, TypeError):
return None
def proc_env_value(pid: int, name: str) -> str | None:
try:
for item in Path(f'/proc/{int(pid)}/environ').read_bytes().split(b'\0'):
key, sep, value = item.partition(b'=')
if sep and key.decode(errors='ignore') == name:
return value.decode('utf-8', errors='replace')
except (OSError, ValueError, TypeError):
pass
return None
def worker_resource_budget_snapshot(pid: int | None) -> dict[str, Any]:
"""Expose a credential-free subset of the live worker's boot budget."""
if not isinstance(pid, int) or pid <= 0:
return {}
wanted = {
*WORKER_BUDGET_STATUS_KEYS,
RESOURCE_BUDGET_POLICY_ENV,
RESOURCE_BUDGET_AUTOMATIC_ENV,
}
found: dict[str, str] = {}
try:
for item in Path(f'/proc/{pid}/environ').read_bytes().split(b'\0'):
key_bytes, separator, value_bytes = item.partition(b'=')
if not separator:
continue
key = key_bytes.decode('utf-8', errors='ignore')
if key in wanted:
found[key] = value_bytes.decode('utf-8', errors='replace')
except (OSError, ValueError, TypeError):
return {}
automatic = sorted({
name for name in found.get(
RESOURCE_BUDGET_AUTOMATIC_ENV, '').split(',')
if name in RESOURCE_BUDGET_ENV_KEYS
})
policy_version = found.get(RESOURCE_BUDGET_POLICY_ENV, '')
return {
'policyVersion': policy_version or None,
'currentPolicyVersion': RESOURCE_BUDGET_POLICY_VERSION,
'policyCurrent': policy_version == RESOURCE_BUDGET_POLICY_VERSION,
'automatic': automatic,
'values': {
name: found[name]
for name in WORKER_BUDGET_STATUS_KEYS
if name in found
},
}
def proc_cmdline(pid: int) -> str | None:
try:
return Path(f'/proc/{int(pid)}/cmdline').read_bytes().replace(b'\0', b' ').decode(
'utf-8', errors='replace').strip()
except (OSError, ValueError, TypeError):
return None
def proc_cwd(pid: int) -> str | None:
try:
return os.path.realpath(os.readlink(f'/proc/{int(pid)}/cwd'))
except (OSError, ValueError, TypeError):
return None
def pid_is_alive(pid: int) -> bool:
try:
os.kill(int(pid), 0)
except (OSError, ValueError, TypeError):
return False
try:
stat = Path(f'/proc/{int(pid)}/stat').read_text(encoding='utf-8')
rest = stat[stat.rfind(')') + 2:].split()
if rest and rest[0] == 'Z':
return False
except OSError:
pass
return True
def pid_is_server(pid: int) -> bool:
if not pid_is_alive(pid):
return False
cmdline = proc_cmdline(pid)
# An unreadable live process is ambiguous: report it as live so start
# fails closed. Stop applies stricter identity checks before signalling.
return cmdline is None or 'server.py' in cmdline
_OFFLINE_STORAGE_COMMAND_LABELS = (
('scripts/storage_deep_clean.py', 'SQLite deep clean'),
('scripts/migrate_sqlite_to_postgres.py',
'SQLite to PostgreSQL migration'),
)
_OFFLINE_STORAGECTL_COMMANDS = frozenset({
'baseline', 'integrity-check', 'restore', 'handoff',
})
def _legacy_storage_lease_owner(cmdline: str | None) -> tuple[str, str]:
"""Classify old lease stamps without exposing the holder's command line."""
command = str(cmdline or '')
for marker, label in _OFFLINE_STORAGE_COMMAND_LABELS:
if marker in command:
return 'offline_maintenance', label
if 'scripts/storagectl.py' in command:
try:
arguments = set(shlex.split(command))
except ValueError:
arguments = set(command.split())
operation = next(
(item for item in _OFFLINE_STORAGECTL_COMMANDS
if item in arguments),
None,
)
if operation:
return 'offline_maintenance', f'Storage {operation}'
if '-m lib.storage_sidecar' in command:
return 'storage_sidecar', 'Storage sidecar'
return 'unknown', 'Storage operation'
def read_storage_lease_status(data_dir: str | Path) -> dict[str, Any]:
"""Inspect one storage lease using its OS lock as the sole authority.
The JSON stamp is diagnostic metadata only. A stale ``status=running``
stamp never blocks startup; conversely, an unreadable held lock remains a
fail-closed unknown owner. Returned data deliberately excludes command
lines, lease IDs and authority paths so the manager API cannot leak
operator arguments or credentials.
"""
root = Path(data_dir)
lock_path = root / '.storage-sidecar.lock'
lease_path = root / '.storage-sidecar-lease.json'
result: dict[str, Any] = {
'held': False,
'kind': None,
'label': None,
'pid': None,
'host': None,
'startedAt': None,
'ageSeconds': None,
'holderVerified': False,
}
if not lock_path.is_file():
return result
try:
handle = lock_path.open('r+b')
except OSError:
return {
**result,
'held': True,
'kind': 'unknown',
'label': 'Storage operation',
}
try:
try:
if os.name == 'nt': # pragma: no cover - Windows CI
import msvcrt
handle.seek(0)
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
return result
except (OSError, BlockingIOError):
result['held'] = True
finally:
handle.close()
stamp = _read_json(lease_path)
host = str(stamp.get('host') or '').strip()[:255] or None
try:
pid = int(stamp.get('pid'))
if pid <= 1:
pid = None
except (TypeError, ValueError):
pid = None
try:
started_at = float(stamp.get('started_unix_ms')) / 1000.0
if started_at <= 0:
started_at = None
except (TypeError, ValueError):
started_at = None
kind = str(stamp.get('owner_kind') or '').strip().lower()
label = ' '.join(str(stamp.get('owner_label') or '').split())[:120]
known_kinds = {'offline_maintenance', 'storage_sidecar', 'storage_operation'}
if kind not in known_kinds:
kind = ''
same_host = bool(host and host == _hostname())
process_alive = bool(pid and same_host and pid_is_alive(pid))
if process_alive:
inferred_kind, inferred_label = _legacy_storage_lease_owner(
proc_cmdline(pid))
if not kind or inferred_kind == 'offline_maintenance':
kind = inferred_kind
label = inferred_label
if not kind:
kind = 'unknown'
if not label:
label = {
'offline_maintenance': 'Offline storage maintenance',
'storage_sidecar': 'Storage sidecar',
'storage_operation': 'Storage operation',
}.get(kind, 'Storage operation')
age_seconds = (
max(0.0, _now() - started_at) if started_at is not None else None)
return {
**result,
'kind': kind,
'label': label,
'pid': pid,
'host': host,
'startedAt': started_at,
'ageSeconds': round(age_seconds, 1) if age_seconds is not None else None,
'holderVerified': process_alive,
}
def read_lock_status(project_path: str) -> dict[str, Any]:
project = os.path.realpath(project_path)
lock_path = Path(project) / 'data' / '.server.lock'
result: dict[str, Any] = {
'projectPath': project,
'running': False,
'pid': None,
'host': None,
'sameHost': None,
'lockPresent': lock_path.is_file(),
'stale': False,
'processStartTime': None,
'processStartedAt': None,
'processCwd': None,
'projectMatches': None,
'cmdline': None,
'externalOwner': None,
}
if not result['lockPresent']:
return result
try:
entry = (lock_path.read_text(encoding='utf-8').splitlines() or [''])[0].strip()
except OSError:
result['stale'] = True
return result
if '@' not in entry:
result['stale'] = True
return result
raw_pid, _, host = entry.partition('@')
if not raw_pid.isdigit():
result['stale'] = True
return result
pid = int(raw_pid)
result['pid'] = pid
result['host'] = host or None
result['sameHost'] = (host == _hostname()) if host else None
result['processStartTime'] = proc_start_ticks(pid)
result['processStartedAt'] = proc_start_epoch(pid)
result['processCwd'] = proc_cwd(pid)
result['projectMatches'] = (
result['processCwd'] == project if result['processCwd'] is not None else None)
result['cmdline'] = proc_cmdline(pid)
result['externalOwner'] = proc_env_value(pid, 'TOFU_MANAGED_BY')
if result['sameHost'] is False:
return result
if pid_is_server(pid):
result['running'] = True
else:
result['stale'] = True
return result
def listener_pids(port: int) -> list[int]:
"""Return listener PIDs visible through ss; [] also means unavailable."""
try:
out = subprocess.run(
['ss', '-ltnp'], capture_output=True, text=True, timeout=3,
).stdout
except (OSError, subprocess.SubprocessError):
return []
found: set[int] = set()
suffix = f':{int(port)}'
for line in out.splitlines():
cols = line.split()
if not any(col.endswith(suffix) for col in cols[:6]):
continue
marker = 'pid='
start = 0
while True:
at = line.find(marker, start)
if at < 0:
break
digits = []
for ch in line[at + len(marker):]:
if not ch.isdigit():
break
digits.append(ch)
if digits:
found.add(int(''.join(digits)))
start = at + len(marker)
return sorted(found)
def port_accepts(port: int, host: str = '127.0.0.1', timeout: float = 0.5) -> bool:
try:
with socket.create_connection((host, int(port)), timeout=timeout):
return True
except OSError:
return False
def _valid_server_port(raw: Any) -> int | None:
try:
port = int(raw)
except (ValueError, TypeError):
return None
return port if 1 <= port <= 65535 else None
HTTP_PROBE_RESPONSE_LIMIT = 64 * 1024
def _read_probe_json(
url: str, *, timeout: float, context: ssl.SSLContext | None = None,
) -> tuple[int, dict[str, Any]]:
"""Read one bounded JSON probe response, including structured HTTP errors."""
try:
with urllib.request.urlopen(
url, timeout=timeout, context=context) as response:
status = int(response.status)
body = response.read(HTTP_PROBE_RESPONSE_LIMIT + 1)
except urllib.error.HTTPError as exc:
status = int(exc.code)
try:
body = exc.read(HTTP_PROBE_RESPONSE_LIMIT + 1)
finally:
exc.close()
if len(body) > HTTP_PROBE_RESPONSE_LIMIT:
raise ValueError(
f'probe response exceeds {HTTP_PROBE_RESPONSE_LIMIT} bytes')
payload = json.loads(body.decode('utf-8') or '{}')
if not isinstance(payload, dict):
raise ValueError('probe response must be a JSON object')
return status, payload
def _readiness_failure_detail(
status: int, payload: dict[str, Any],
) -> str:
error = payload.get('error')
error_code = ''
error_message = ''
if isinstance(error, dict):
error_code = str(error.get('code') or '').strip()
error_message = str(error.get('message') or '').strip()
elif error:
error_message = str(error).strip()
message = str(payload.get('message') or error_message or '').strip()
state = str(payload.get('state') or 'unknown').strip()
storage = payload.get('storage')
storage_state = (
str(storage.get('state') or 'unknown').strip()
if isinstance(storage, dict) else 'unknown')
reason = ': '.join(part for part in (error_code, message) if part)
suffix = f'lifecycle={state}, storage={storage_state}, HTTP {status}'
return f'{reason}; {suffix}' if reason else suffix
def _settle_readiness_probe(
result: dict[str, Any],
*,
scheme: str,
port: int,
status: int,
payload: dict[str, Any],
) -> dict[str, Any]:
"""Project one already-fetched readiness response onto a live worker."""
storage = payload.get('storage')
readiness_state = payload.get('state')
storage_state = storage.get('state') if isinstance(storage, dict) else None
ready = bool(
200 <= status < 300
and payload.get('ok') is True
and payload.get('ready') is True)
result.update({
'ready': ready,
'readinessState': readiness_state,
'storageState': storage_state,
})
if ready:
result['url'] = f'{scheme}://localhost:{port}'
return result
detail = 'application readiness failed: ' + _readiness_failure_detail(
status, payload)
result.update(readinessError=detail, error=detail)
return result
def probe_application_readiness(
port: int,
expected_pid: int | None,
*,
preferred_scheme: str = '',
timeout: float = 2.0,
) -> dict[str, Any]:
"""Verify loopback worker identity and its dependency readiness.
``health`` remains a compatibility alias for identity liveness. It must
not be used as traffic readiness; callers require both ``liveness`` and
``ready``. Current workers return their PID from ``/api/ready``, allowing
one normal probe. Older workers fall back to the two-endpoint contract.
"""
result: dict[str, Any] = {
'health': False,
'liveness': False,
'ready': False,
'scheme': None,
'url': None,
'liveUrl': None,
'payloadPid': None,
'pidMatches': False,
'livenessError': '',
'readinessError': '',
'readinessState': None,
'storageState': None,
}
checked_port = _valid_server_port(port)
if checked_port is None:
result['livenessError'] = f'invalid application port: {port!r}'
result['error'] = result['livenessError']
return result
if not isinstance(expected_pid, int):
result['livenessError'] = 'locked worker PID is unavailable'
result['error'] = result['livenessError']
return result
schemes = ([preferred_scheme]
if preferred_scheme in ('http', 'https') else [])
schemes.extend(
scheme for scheme in ('http', 'https') if scheme not in schemes)
last_error = ''
for scheme in schemes:
context = ssl._create_unverified_context() if scheme == 'https' else None
base_url = f'{scheme}://127.0.0.1:{checked_port}'
ready_status = None
ready_payload = None
ready_error = ''
try:
ready_status, ready_payload = _read_probe_json(
base_url + '/api/ready', timeout=timeout, context=context)
except (OSError, ValueError, urllib.error.URLError,
json.JSONDecodeError) as exc:
ready_error = f'{scheme} readiness probe failed: {exc}'
if ready_payload is not None and ready_payload.get('pid') is not None:
payload_pid = ready_payload.get('pid')
if payload_pid != expected_pid:
last_error = (
'readiness response PID does not match the locked worker '
f'(expected {expected_pid}, got {payload_pid})')
continue
result.update({
'health': True,
'liveness': True,
'scheme': scheme,
'liveUrl': f'{scheme}://localhost:{checked_port}',
'payloadPid': payload_pid,
'pidMatches': True,
'livenessError': '',
})
return _settle_readiness_probe(
result,
scheme=scheme,
port=checked_port,
status=int(ready_status),
payload=ready_payload,
)
# Compatibility path for a worker generation whose readiness payload
# predates the PID field, or when readiness transport itself failed.
try:
health_status, health_payload = _read_probe_json(
base_url + '/api/health', timeout=timeout, context=context)
except (OSError, ValueError, urllib.error.URLError,
json.JSONDecodeError) as exc:
last_error = f'{scheme} identity liveness probe failed: {exc}'
continue
payload_pid = health_payload.get('pid')
pid_matches = payload_pid == expected_pid
live = bool(
200 <= health_status < 300
and health_payload.get('ok') is True
and pid_matches)
if not live:
if not pid_matches:
last_error = (
'identity liveness response PID does not match the '
f'locked worker (expected {expected_pid}, got {payload_pid})')
else:
last_error = (
f'identity liveness probe returned HTTP {health_status} '
'without ok=true')
continue
result.update({
'health': True,
'liveness': True,
'scheme': scheme,
'liveUrl': f'{scheme}://localhost:{checked_port}',
'payloadPid': payload_pid,
'pidMatches': True,
'livenessError': '',
})
if ready_payload is None:
detail = ready_error or f'{scheme} readiness probe failed'
result.update(readinessError=detail, error=detail)
return result
return _settle_readiness_probe(
result,
scheme=scheme,
port=checked_port,
status=int(ready_status),
payload=ready_payload,
)
result['livenessError'] = last_error or 'identity liveness probe failed'
result['error'] = result['livenessError']
return result
def _explicit_server_port(args: list[str]) -> int | None:
for index, arg in enumerate(args):
if arg == '--port' and index + 1 < len(args):
return _valid_server_port(args[index + 1])
if arg.startswith('--port='):
return _valid_server_port(arg.partition('=')[2])
return None
def _server_port(args: list[str], env: dict[str, str] | None = None) -> int:
explicit = _explicit_server_port(args)
if explicit is not None:
return explicit
source = env if env is not None else os.environ
return _valid_server_port(source.get('PORT')) or DEFAULT_SERVER_PORT
def _live_worker_port(status: dict[str, Any]) -> tuple[int | None, str]:
"""Return a verified worker's self-declared bind port and its source.
The lifecycle state is durable intent, not proof of what an adopted or
in-place re-executed process actually serves. Prefer argv because it wins
over ``PORT`` in ``server.py``; fall back to the process environment for a
normal manager spawn. Callers must establish worker identity first.
"""
cmdline = status.get('cmdline')
if isinstance(cmdline, str) and cmdline.strip():
try:
args = shlex.split(cmdline)
except ValueError:
args = cmdline.split()
explicit = _explicit_server_port(args)
if explicit is not None:
return explicit, 'argv'
pid = status.get('pid')
if isinstance(pid, int):
for name in ('_TOFU_RUNTIME_PORT', 'PORT'):
observed = _valid_server_port(proc_env_value(pid, name))
if observed is not None:
return observed, f'env:{name}'
return None, ''
def _rewrite_explicit_server_port(args: list[str], port: int) -> list[str]:
"""Keep stored argv consistent when an adopted worker corrects its port."""
rewritten = list(args)
for index, arg in enumerate(rewritten):
if arg == '--port' and index + 1 < len(rewritten):
rewritten[index + 1] = str(port)
return rewritten
if arg.startswith('--port='):
rewritten[index] = f'--port={port}'
return rewritten
return rewritten
def project_server_env(project_path: str) -> dict[str, str]:
"""Read lifecycle-relevant values from the project's simple .env file."""
result: dict[str, str] = {}
try:
lines = (Path(project_path) / '.env').read_text(encoding='utf-8').splitlines()
except OSError:
return result
for raw in lines:
line = raw.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, _, value = line.partition('=')
key = key.strip()
if key in SERVER_ENV_KEYS:
result[key] = value.strip().strip('"').strip("'")
return result
def _path_is_pytest_owned(raw_path: object, project_path: str) -> bool:
"""Return whether a path is inside a recognizable pytest-owned root."""
value = str(raw_path or '').strip()
if not value:
return False
try:
path = Path(value).expanduser()
if not path.is_absolute():
path = Path(project_path) / path
parts = path.resolve(strict=False).parts
except (OSError, RuntimeError, ValueError):
return False
for part in parts:
if part.startswith(('tofu-pytest-runs-', 'tofu-test-data-',
'tofu-test-storage-')):
return True
if part.startswith('pytest-of-'):
return True
if part.startswith('pytest-') and part[7:].isdigit():
return True
if part.startswith('popen-gw') and part[8:].isdigit():
return True
return False
def production_server_environment_error(
project_path: str,
environment: dict[str, object],
) -> str:
"""Reject test-owned state from a non-test (production) checkout.
Test projects are allowed to use their disposable data roots. The unsafe
combination is a durable/real checkout plus either a pytest process marker
or a data-location variable rooted in pytest's temporary namespace.
"""
if _path_is_pytest_owned(project_path, project_path):
return ''
for key in _DATA_LOCATION_ENV_KEYS:
if _path_is_pytest_owned(environment.get(key), project_path):
return (
f'production lifecycle refused: {key} points into '
'pytest-owned temporary storage')
for key in _PYTEST_CONTEXT_ENV_KEYS:
if str(environment.get(key) or '').strip():
return (
f'production lifecycle refused: inherited pytest context '
f'({key})')
if str(environment.get('TOFU_TESTING') or '').strip() == '1':
return 'production lifecycle refused: inherited pytest context (TOFU_TESTING)'
return ''
def run_frontend_preflight(
project_path: str,
python_executable: str,
environment: dict[str, str],
operation: str,
) -> tuple[bool, str]:
"""Run the project's repair-capable frontend gate in an isolated process.
The manager intentionally imports no application dependency graph. The
child command owns role selection, content-digest validation, the shared
build lock, and optional Node repair. Its output inherits the bounded
manager log rather than accumulating in an in-memory capture buffer.
"""
command_path = Path(project_path) / 'serverctl.py'
if not command_path.is_file():
return False, f'frontend preflight command is missing: {command_path}'
child_environment = dict(environment)
child_environment['TOFU_PROJECT_PATH'] = str(Path(project_path).resolve())
try:
completed = subprocess.run(
[
python_executable,
str(command_path),
'prepare-frontend',
'--operation',
str(operation or 'manager worker spawn')[:120],
],
cwd=project_path,
env=child_environment,
stdin=subprocess.DEVNULL,
timeout=DEFAULT_FRONTEND_PREFLIGHT_TIMEOUT,
check=False,
)
except subprocess.TimeoutExpired:
return False, (
'frontend preflight exceeded '
f'{DEFAULT_FRONTEND_PREFLIGHT_TIMEOUT:.0f}s')
except OSError as exc:
return False, f'frontend preflight could not start: {exc}'
if completed.returncode:
return False, (
f'frontend preflight exited {completed.returncode}; '
'see the manager log for the validation/build error')
return True, ''
class LifecycleManager:
"""Own exactly one project's desired/observed server state."""
def __init__(self, project_path: str, python_exe: str | None = None,
*, monitor_interval: float | None = None) -> None:
self.project = os.path.realpath(project_path)
self.python = python_exe or os.environ.get('TOFU_SUPERVISOR_PYTHON') or sys.executable
self.data_dir = Path(self.project) / 'data'
self.logs_dir = Path(self.project) / 'logs'
self.state_path = self.data_dir / 'server-manager-state.json'
self.worker_log = self.logs_dir / 'server-console.log'
self._last_log_maintenance_at = 0.0
self._last_monitor_error = ''
self._monitor_error_count = 0
self._lock = threading.RLock()
self._stop_event = threading.Event()
self._monitor: threading.Thread | None = None
self._worker_bytecode_cache_lock_fd: int | None = None
self._state_needs_save = False
self._project_env = project_server_env(self.project)
loaded = _read_json(self.state_path)
self._had_state = loaded.get('version') == STATE_VERSION
try:
configured = float(os.environ.get('TOFU_MANAGER_INTERVAL', '') or
(monitor_interval or DEFAULT_MONITOR_INTERVAL))
except (ValueError, TypeError):
configured = DEFAULT_MONITOR_INTERVAL
self.monitor_interval = max(0.2, configured)
try:
failure_window = float(
os.environ.get('TOFU_MANAGER_FAILURE_WINDOW_SECS', '') or
DEFAULT_FAILURE_WINDOW)
except (ValueError, TypeError):
failure_window = DEFAULT_FAILURE_WINDOW
self.failure_window = max(30.0, min(3600.0, failure_window))
try:
max_failures = int(
os.environ.get('TOFU_MANAGER_MAX_FAILURES', '') or
DEFAULT_MAX_FAILURES)
except (ValueError, TypeError):
max_failures = DEFAULT_MAX_FAILURES
self.max_failures = max(2, min(100, max_failures))
rss_limit_mb = (
os.environ.get('TOFU_PROCESS_RSS_RECYCLE_MB')
or self._project_env.get('TOFU_PROCESS_RSS_RECYCLE_MB'))
profile_environment = dict(os.environ)
profile_environment.update(self._project_env)
self.worker_rss_recycle_bytes = worker_rss_recycle_limit_bytes(
rss_limit_mb, environment=profile_environment)
self._state = self._load_state()
if self._state_needs_save:
self._save()
self._adopt_existing()
self._restore_worker_bytecode_cache_lease()
def _default_state(self) -> dict[str, Any]:
default_env = dict(self._project_env)
return {
'version': STATE_VERSION,
'projectPath': self.project,
'desired': 'stopped',
'observed': 'stopped',