release: Themiz на Gitea

This commit is contained in:
public-repo-gate
2026-10-19 11:10:53 +03:00
parent e52e76d4ea
commit 067c6c2414
225 changed files with 240125 additions and 26157 deletions
+76 -25
View File
@@ -28,10 +28,14 @@ JOB_SECONDS = 120.0
TICK_SECONDS = 180.0
LEASE_SECONDS = 240.0
REPORT_GRACE_SECONDS = 2.0
# Остаток тика меньше - новое задание не берем: за 2 с источник не успевает, а попытка сгорает.
MIN_SLICE_SECONDS = 20.0
MIN_FREE_BYTES = 1024 ** 3
SCHEDULER_PATH = os.pathsep.join((str(Path(sys.executable).parent), "/usr/local/bin",
"/opt/homebrew/bin", str(Path.home() / ".npm-global" / "bin"),
"/usr/bin", "/bin", "/usr/sbin", "/sbin"))
# launchd не читает ~/.zshenv: без пула fake-IP VPN Lynceuz отказывает policy_denied каждому источнику.
SCHEDULER_ENV = ("LYNCEUZ_FAKE_IP_POOLS",)
ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\Z")
@@ -290,8 +294,18 @@ def enqueue_registered(root: Path, ids: set[str] | list[str] | None = None, *, f
def enqueue_all(root: Path, *, force: bool = False) -> list[dict]:
"""Публичный ручной запуск всей зарегистрированной очереди."""
return enqueue_registered(root, force=force)
"""Публичный ручной запуск всей очереди: реестр и найденное каталогом, но еще не скачанное.
Реестр строится по файлам корпуса: у ресурса, который ни разу не скачался, строки реестра нет.
"""
root = _safe_root(root)
jobs = enqueue_registered(root, force=force)
known = {job["id"] for job in jobs}
for job in status(root)["jobs"]:
item = None if job["id"] in known else _queued_resource(root, job["id"])
if item is not None:
jobs.append(_enqueue_validated(root, _registry_validate(root, item), force=force))
return jobs
def _queued_resource(root: Path, resource_id: str) -> dict | None:
@@ -341,24 +355,21 @@ def status(root: Path, resource_id: str | None = None) -> dict:
return {"ok": True, "queue": counts, "jobs": jobs}
def _loaded() -> bool:
return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
def schedule(root: Path) -> dict:
"""Стабильная сводка расписания для локального cockpit API."""
root = _safe_root(root)
policy_enabled = enabled(root)
target = _agents_dir() / f"{LABEL}.plist"
plist_matches = False
if target.exists() and not target.is_symlink():
try:
plist_matches = plistlib.loads(target.read_bytes()) == _payload(root)
except (OSError, ValueError, plistlib.InvalidFileException):
plist_matches = False
own = _installed()
plist_matches = own is not None and own == _payload(root, own)
loaded = False
if plist_matches:
if own is not None: # путь к python в plist зависит от того, кто ставил задачу; загрузку знает launchctl
try:
loaded = subprocess.run(
["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
).returncode == 0
loaded = _loaded()
except OSError:
loaded = False
overview = status(root)
@@ -479,8 +490,8 @@ def _run_isolated(root: Path, resource: dict, state_dir: Path, seconds: float) -
process.start()
started = True
child.close()
wait_ready = max(0.0, min(5.0, end - time.monotonic()))
if not parent.poll(wait_ready):
# Под нагрузкой процесс с QoS Background стартовал 13 с (замер 03.10.2026): ready ждем весь бюджет задания.
if not parent.poll(max(0.0, end - time.monotonic())):
return {"status": "deferred", "detail": "worker не запустился в срок"}
message = parent.recv()
if not isinstance(message, dict) or message.get("ready") is not True:
@@ -639,7 +650,7 @@ def tick(root: Path, *, max_seconds: float = TICK_SECONDS, job_seconds: float =
"stopped_reason": "official_sources_not_approved"}
while True:
remaining = max_seconds - (time.monotonic() - started)
if remaining <= 0:
if remaining < min(MIN_SLICE_SECONDS, max_seconds):
reason = "tick_deadline"
break
claimed = _claim(root, time.time())
@@ -692,7 +703,30 @@ def _agents_dir() -> Path:
return Path.home() / "Library" / "LaunchAgents"
def _payload(root: Path) -> dict:
def _installed() -> dict | None:
"""plist этой задачи или None: нет, битый или чужой под той же меткой."""
target = _agents_dir() / f"{LABEL}.plist"
try:
value = None if target.is_symlink() else plistlib.loads(target.read_bytes())
except (OSError, ValueError, plistlib.InvalidFileException):
return None
script = str(ROOT / "scripts" / "background_corpus.py")
own = (isinstance(value, dict) and value.get("Label") == LABEL
and script in (value.get("ProgramArguments") or []))
return value if own else None
def scheduler_env(old: dict | None = None) -> dict:
"""SCHEDULER_ENV из окружения, иначе из установленной задачи.
Сервер Эвномии поднимает раннер launchd: в его окружении пула нет, а тик сервера ходит в сеть.
"""
kept = (old if old is not None else _installed() or {}).get("EnvironmentVariables") or {}
values = {name: os.environ.get(name) or kept.get(name) for name in SCHEDULER_ENV}
return {name: value for name, value in values.items() if isinstance(value, str) and value}
def _payload(root: Path, old: dict | None = None) -> dict:
return {
"Label": LABEL,
"ProgramArguments": ["/usr/bin/nice", "-n", "10", sys.executable,
@@ -702,7 +736,7 @@ def _payload(root: Path) -> dict:
"RunAtLoad": True,
"ProcessType": "Background",
"LowPriorityIO": True,
"EnvironmentVariables": {"PATH": SCHEDULER_PATH},
"EnvironmentVariables": {"PATH": SCHEDULER_PATH, **scheduler_env(old)},
"WorkingDirectory": str(root),
"StandardOutPath": str(_directory(root) / "launchd.log"),
"StandardErrorPath": str(_directory(root) / "launchd.err.log"),
@@ -738,10 +772,21 @@ def install(root: Path) -> dict:
agents = _agents_dir()
agents.mkdir(parents=True, exist_ok=True)
target = agents / f"{LABEL}.plist"
payload = _payload(root)
old = _installed()
if (target.exists() or target.is_symlink()) and old is None:
raise FileExistsError("чужой plist не перезаписан")
payload = _payload(root, old)
if old is not None and old != payload: # своя задача с прежним окружением или python: заменить
subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(30): # bootout возвращается раньше, чем задача остановится
if not _loaded():
break
time.sleep(1)
else:
raise RuntimeError("прежняя задача не остановилась за 30 с; повторите install")
target.unlink()
if target.exists():
if target.is_symlink() or plistlib.loads(target.read_bytes()) != payload:
raise FileExistsError("чужой plist не перезаписан")
probe = subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if probe.returncode != 0:
@@ -776,7 +821,7 @@ def uninstall(root: Path) -> dict:
if not target.exists():
_set_enabled(root, False)
return {"status": "absent", "label": LABEL}
if target.is_symlink() or plistlib.loads(target.read_bytes()) != _payload(root):
if _installed() is None:
raise FileExistsError("чужой plist не удален")
subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -785,6 +830,11 @@ def uninstall(root: Path) -> dict:
return {"status": "uninstalled", "label": LABEL}
# Сборка графа права - 90 с на 449 документах (замер 03.10.2026). Прежние 60 с убивали каждую сборку
# после тика: снимок не обновлялся, в legal-graph/ копились брошенные .build-*.
GRAPH_SECONDS = 300
def refresh_graph_after_tick(root: Path, result: dict) -> dict:
"""Только фоновый CLI: независимая недельная сборка после загрузчика."""
if result.get("stopped_reason") in {
@@ -799,7 +849,7 @@ def refresh_graph_after_tick(root: Path, result: dict) -> dict:
completed = subprocess.run(
[sys.executable, str(graph_script),
"--refresh", "--root", str(root), "--json"],
capture_output=True, text=True, timeout=60, check=False,
capture_output=True, text=True, timeout=GRAPH_SECONDS, check=False,
)
outcome = json.loads(completed.stdout)
if not isinstance(outcome, dict):
@@ -808,7 +858,7 @@ def refresh_graph_after_tick(root: Path, result: dict) -> dict:
outcome["returncode"] = completed.returncode
return outcome
except subprocess.TimeoutExpired:
return {"status": "deferred", "reason": "graph_deadline_60s",
return {"status": "deferred", "reason": f"graph_deadline_{GRAPH_SECONDS}s",
"last_good_preserved": True}
except (OSError, ValueError) as exc:
return {"status": "failed", "reason": type(exc).__name__, "last_good_preserved": True}
@@ -834,6 +884,7 @@ def main(argv: list[str] | None = None) -> int:
elif args.schedule:
result = schedule(args.root)
elif args.tick:
os.environ.update(scheduler_env()) # тик сервера и раннера: пул из установленной задачи
registry_error = None
if enabled(args.root) and _approved(args.root):
try: