Six private readers repeated the body of utils.read_json_or_empty
line for line: read utf-8-sig, return {} on OSError or ValueError,
return {} for a JSON value that is not an object.
rich_sent_store._load and stuck_loop_counts._read_counts only took a
path, so they are deleted and their callers call read_json_or_empty.
prune_advisor._read_estimate, webapp_access._registration,
left_core_migration._auth_store and local_runtime.recovery.read_state
compute their path, so they keep their names and read through the
shared helper. utils is imported inside the function where the module
already imports utils lazily, so module import cost is unchanged.
boot_bootstrap.read_last_known stays: it is boot code that imports no
utils, and it is a public name other modules import.
environments/base._load_json_store stays: modal.py and
vercel_sandbox.py import it.
47 lines
1.8 KiB
Python
47 lines
1.8 KiB
Python
"""Persisted per-session restart-failure counters (``.restart_failure_counts``, #7536).
|
|
|
|
Every load/mutate/save of the file runs under one lock: session completions clear their
|
|
counter from worker threads concurrently, and an unserialized pair rewrites a stale snapshot
|
|
that resurrects the other session's counter.
|
|
"""
|
|
|
|
import logging
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Nothing re-acquires it while held, so a plain Lock suffices.
|
|
_COUNTS_LOCK = threading.Lock()
|
|
|
|
|
|
def increment_restart_failure_counts(path: Path, active_session_keys: set) -> None:
|
|
"""Increment the counters of sessions active at shutdown; drop the rest (their loop is broken)."""
|
|
from utils import atomic_json_write, read_json_or_empty
|
|
with _COUNTS_LOCK:
|
|
counts = read_json_or_empty(path)
|
|
try:
|
|
atomic_json_write(path, {key: counts.get(key, 0) + 1 for key in active_session_keys}, indent=None)
|
|
except Exception:
|
|
logger.debug("Could not write restart-failure counters to %s", path, exc_info=True)
|
|
|
|
|
|
def clear_restart_failure_count(path: Path, session_key: str) -> None:
|
|
"""Drop a completed session's counter; removes the file once no counter is left.
|
|
|
|
Blocking (``atomic_json_write`` fsyncs): callers on the event loop run it via ``asyncio.to_thread``.
|
|
"""
|
|
from utils import atomic_json_write, read_json_or_empty
|
|
with _COUNTS_LOCK:
|
|
counts = read_json_or_empty(path)
|
|
if session_key not in counts:
|
|
return
|
|
del counts[session_key]
|
|
try:
|
|
if counts:
|
|
atomic_json_write(path, counts, indent=None)
|
|
else:
|
|
path.unlink(missing_ok=True)
|
|
except Exception:
|
|
logger.debug("Could not clear restart-failure counter in %s", path, exc_info=True)
|