File size: 8,103 Bytes
4606829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Foreground owned engine window; controller lock held until prior restore."""
from pathlib import Path
import argparse
import json
import os
import signal
import shlex
import http.client
import subprocess
import sys
import time

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
try:
    import stack_controller
except ImportError:
    stack_controller = None


def small_idle_llama(argv, *, query=None):
    """Permit only a verified <=2GiB, <=8k idle loopback native server.

    One-large-engine policy does not authorize stopping unrelated small apps.
    Any missing/unknown ownership, model or processing fact remains blocking.
    """
    try:
        def option(*names):
            for name in names:
                if name in argv:return argv[argv.index(name)+1]
            return None
        weight = Path(option('-m', '--model')).resolve()
        host = option('--host')
        port = int(option('--port'))
        if host not in ('localhost', '127.0.0.1') or not 1 <= port <= 65535:
            return False
        if not weight.is_file() or weight.stat().st_size > 2 * 1024**3:
            return False
        def request(port, path):
            connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
            try:
                connection.request('GET', path)
                response = connection.getresponse()
                if response.status != 200:return None
                return json.loads(response.read())
            finally:connection.close()
        get = query or request
        props, slots = get(port, '/props'), get(port, '/slots')
        return bool(isinstance(props, dict) and Path(props.get('model_path', '')).resolve() == weight
                    and isinstance(slots, list) and slots and all(
                        isinstance(slot, dict) and slot.get('is_processing') is False
                        and type(slot.get('n_ctx')) is int and 0 < slot['n_ctx'] <= 8192
                        for slot in slots))
    except (OSError, ValueError, TypeError, IndexError, http.client.HTTPException):
        return False


def external_accelerator_work():
    """Conservative process-name guard; never reads/prints private task payloads."""
    rows = subprocess.check_output(['ps', '-axo', 'pid=,command='], text=True)
    candidates = []
    markers = {'encoder_experiment.py': 'encoder_training',
               'image_tool.py --': 'image_generation', 'sd-server': 'image_backend',
               'mlx_vlm server': 'mlx_server', 'mlx_dspark serve': 'mlx_server',
               'llama-server': 'llama_server'}
    for row in rows.splitlines():
        fields = row.strip().split(None, 1)
        if len(fields) != 2 or int(fields[0]) == os.getpid():
            continue
        command = fields[1]
        # Parent shells can carry the worker command in their -c script; do not
        # mistake our own launch wrapper for an active GPU worker.
        if command.startswith(('/bin/bash ', '/bin/zsh ', '/usr/bin/bash ')):
            continue
        for marker, kind in markers.items():
            if marker in command:
                if kind == 'llama_server' and small_idle_llama(shlex.split(command)):
                    break
                candidates.append({'pid': int(fields[0]), 'kind': kind})
                break
    return candidates


def run_window(command, output, *, timeout=900, controller=stack_controller,
               external_work=None):
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    receipt = output / 'window.json'
    if receipt.exists():
        raise ValueError('Window output already exists; preserve previous evidence')
    state = {'owner_pid': os.getpid(), 'started_at': time.time(), 'restored': False,
             'authorization': 'operator resume after explicit temporary-pause notice',
             'worker_returncode': None, 'timed_out': False}
    def save():
        receipt.write_text(json.dumps(state, indent=2) + '\n')
    with controller.lock():
        detector = external_work or (external_accelerator_work if controller is stack_controller else lambda: [])
        external = detector()
        state['external_accelerator_jobs'] = external
        if external:
            state['phase'] = 'blocked_before_unload'
            state['restored'] = True  # No state was changed; prior service remains.
            save()
            raise RuntimeError('Another accelerator/GPU job is active; no backend unloaded')
        active = [profile for profile in controller.profiles().values() if controller.occupied(profile.port)]
        if len(active) > 1:
            raise RuntimeError('Multiple engines active; refusing ambiguous ownership')
        if controller.occupied(18800) or controller.occupied(18798):
            raise RuntimeError('Lab engine already active')
        previous = active[0] if active else None
        if previous:
            if previous.kind != 'text' or not controller.loaded(controller.label(previous)):
                raise RuntimeError('Current engine ownership is not verified')
            if not controller.text_snapshot_idle(controller.request_json(previous, '/status')):
                raise RuntimeError('Current engine busy or idle snapshot unknown')
            controller.validate_paths(previous)
        state['restore_profile'] = previous.key if previous else None
        save()
        process = None
        paused = False
        try:
            if previous:
                controller.stop_all()
                paused = True
            state['phase'] = 'worker'
            save()
            with (output / 'worker.log').open('wb') as log:
                process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT,
                                           stdin=subprocess.DEVNULL, start_new_session=True)
                state['worker_pid'] = process.pid
                save()
                try:
                    state['worker_returncode'] = process.wait(timeout=timeout)
                except subprocess.TimeoutExpired:
                    state['timed_out'] = True
                    os.killpg(process.pid, signal.SIGTERM)
                    try:
                        process.wait(timeout=20)
                    except subprocess.TimeoutExpired:
                        os.killpg(process.pid, signal.SIGKILL)
                        process.wait()
                    state['worker_returncode'] = process.returncode
        finally:
            if process is not None and process.poll() is None:
                os.killpg(process.pid, signal.SIGTERM)
                try:
                    process.wait(timeout=20)
                except subprocess.TimeoutExpired:
                    os.killpg(process.pid, signal.SIGKILL)
                    process.wait()
            state['phase'] = 'restoring'
            try:
                save()
            finally:
                if paused:
                    controller.start_locked(previous, quiet=True)
                    state['restored'] = controller.status(previous)['api_ready']
                else:
                    state['restored'] = previous is None
                state['phase'] = 'finished' if state['restored'] else 'restore_failed'
                state['finished_at'] = time.time()
                save()
            if not state['restored']:
                raise RuntimeError('Prior service restoration failed; inspect window receipt')
    return state


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--timeout', type=float, default=900)
    parser.add_argument('command', nargs=argparse.REMAINDER)
    args = parser.parse_args()
    command = args.command[1:] if args.command[:1] == ['--'] else args.command
    if not command:
        parser.error('worker command required')
    result = run_window(command, args.output, timeout=args.timeout)
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result['worker_returncode'] == 0 else 1)