okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-142-engine2' into f-142e85f56209

main
3.2 KiB84 linesraw
1"""Bounded SAVE admission retries after opt-in engine cache reclamation.
2
3The caller holds the service FIFO. Only an unpublished, typed RAM preflight
4refusal is retried, on the same live engine process and with its floor intact.
5No model unload, working-set trim or unrelated process is involved.
6"""
7from __future__ import annotations
8
9import re
10import time
11
12SETTLE_SECONDS = 30.0
13MAX_RETRIES = 3
14POLL_SECONDS = 0.5
15
16
17def required_mib(error) -> int | None:
18    match = re.search(r'^not enough RAM to save the session '
19                      r'\((\d+) MiB plus a floor of (\d+) MiB needed,', str(error))
20    # Each diagnostic term rounds bytes down; two MiB preserve admission headroom.
21    return sum(map(int, match.groups())) + 2 if match else None
22
23
24def available_mib() -> int | None:
25    try:
26        import psutil
27        available = psutil.virtual_memory().available
28        if isinstance(available, bool) or not isinstance(available, int) or available < 0:
29            return None
30        return available // 2**20
31    except (ImportError, OSError, AttributeError, ValueError):
32        return None
33
34
35def retryable(action, error) -> bool:
36    return (action == 'save' and error.kind == 'memory' and not error.published
37            and required_mib(error) is not None)
38
39
40def session_file(service, action, path, refused_type):
41    """Called only when --session-save-reclaim is enabled; never changes RESTORE."""
42    engine = service.engine
43    process = getattr(engine, 'proc', None)
44    try:
45        return engine.session_file(action, path)
46    except refused_type as error:
47        if not retryable(action, error) or process is None:
48            raise
49        deadline = time.monotonic() + SETTLE_SECONDS
50        last_error = error
51
52        def same_process():
53            try:
54                return (service.engine is engine and engine.proc is process
55                        and not getattr(engine, 'ended', False) and process.poll() is None)
56            except OSError:
57                return False
58
59        print('[strata] SAVE waiting for RAM after cache reclaim: '
60              f'need={required_mib(error)} MiB, limit={SETTLE_SECONDS:g}s; floor unchanged', flush=True)
61        for attempt in range(MAX_RETRIES):
62            while True:
63                if not same_process() or time.monotonic() >= deadline:
64                    raise last_error
65                available = available_mib()
66                needed = required_mib(last_error)
67                if available is None or needed is None:
68                    raise last_error
69                if available >= needed:
70                    break
71                time.sleep(max(0.0, min(POLL_SECONDS, deadline - time.monotonic())))
72            # No replacement, restart, or blind retry when telemetry is unknown.
73            if not same_process():
74                raise last_error
75            try:
76                return engine.session_file(action, path)
77            except refused_type as failure:
78                if not retryable(action, failure):
79                    raise
80                last_error = failure
81                if attempt + 1 == MAX_RETRIES or time.monotonic() >= deadline:
82                    raise
83                time.sleep(max(0.0, min(POLL_SECONDS, deadline - time.monotonic())))
84        raise last_error