shared_metrics_update.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. """Shared-metrics facts for ``hermes update`` runs and Desktop self-updates.
  2. ``hermes.update.run`` / ``hermes.update.stage`` are DERIVED from the final update receipt in the
  3. process that finalizes it (``update_receipt.finalize_update_receipt``): the receipt already carries
  4. the outcome, the stage marks with timestamps, the admission refusal and the fleet matrix, so no
  5. stage is instrumented for metrics. A pre-pull interpreter must never import pulled code, so when
  6. it is the finalizer it parks the receipt under the store dir (stdlib-only code in update_receipt)
  7. and :func:`report_pending_updates` records it on the next Hermes start.
  8. Desktop's packaged updaters (electron-updater, App Installer, Store) never run ``hermes update``;
  9. Desktop reports their outcome through the ``shared_metrics.update_run`` RPC instead. Desktop's
  10. source-checkout hand-off DOES run ``hermes update``; that receipt is tagged ``initiator=desktop``
  11. and counted here, never by the RPC, so no run is counted twice.
  12. Run and stage rows agree on where a FAILED run stopped: a run whose ``failed_stage`` names a stage it
  13. never marked (it exited inside it, before the stage's END mark) also gets one failed stage row for it.
  14. A run that passed the commit point and only owes follow-ups (contract C3) is a ``success`` run, while
  15. the stage that failed (``deps``, ``build``, ``restart``, ``verify``) still reads ``failed`` at stage level.
  16. """
  17. from __future__ import annotations
  18. import builtins
  19. import json
  20. import logging
  21. import os
  22. import re
  23. import shutil
  24. import time
  25. from datetime import datetime
  26. from pathlib import Path
  27. from typing import Any
  28. logger = logging.getLogger(__name__)
  29. PENDING_DIRNAME = "pending_updates"
  30. # One empty file per update_id already counted in this profile: the completion child and the
  31. # parent's parked copy can both finalize the same run.
  32. RECORDED_DIRNAME = "recorded_updates"
  33. _RECORDED_KEEP = 64
  34. _UPDATE_ID = re.compile(r"[0-9a-f]{8,64}")
  35. # Receipt pm/Desktop outcome words → hermes.update.run outcome; anything else failed.
  36. _RUN_OUTCOMES = {"success": "success", "refused": "refused", "noop": "noop"}
  37. _FLEET_BAD_STATES = frozenset({"stale", "down"})
  38. # Desktop mechanism (updater strategy kind) → apply_mode.
  39. _DESKTOP_APPLY_MODES = {
  40. "electron-updater": "package", "app-installer": "package", "microsoft-store": "package",
  41. "windows-handoff": "git", "posix-handoff": "git",
  42. }
  43. # ---- iuf c1 ----
  44. # ``finalize_pending_update_receipt`` stores ``f"{type(exc).__name__}: {exc}"`` as the stop reason of
  45. # a run that ended on an exception (main.cmd_update, update_completion._finish). Only the leading
  46. # type name is read, never the message; other stop reasons ("sys.exit(1)", "completion exited 1",
  47. # "Windows gateway recovery failed: ...") do not start with a bare CamelCase name and a colon
  48. # (the fixed prefixes Hermes writes are matched by _STOP_REASON_PREFIX_CLASSES).
  49. _EXCEPTION_STOP_REASON = re.compile(r"([A-Z][A-Za-z0-9_]*):(?: |$)")
  50. # pm's own failure types (pm/package.py, pm/environment.py, pm/downloader.py, pm/lock.py, ...).
  51. _PM_ERROR_TYPES = frozenset({
  52. "BuildFailure", "DownloadError", "DownloadPaused", "DownloadTransportError", "FeatureProbeError",
  53. "HashError", "InstallError", "PinMismatch", "ResolutionConflict", "StaleLockRow",
  54. })
  55. # Built-in OSError and its subclasses (disk full, permissions, a file held open on Windows).
  56. _OS_ERROR_TYPES = frozenset(
  57. name for name, value in vars(builtins).items() if isinstance(value, type) and issubclass(value, OSError))
  58. # subprocess.SubprocessError and its subclasses that reached the command boundary uncaught.
  59. _SUBPROCESS_ERROR_TYPES = frozenset({"CalledProcessError", "SubprocessError", "TimeoutExpired"})
  60. # Exception type name -> class, first match wins; any other type reads ``exception``.
  61. _EXCEPTION_TYPE_CLASSES = (
  62. (frozenset({"PermissionError"}), "permission_denied"), (_PM_ERROR_TYPES, "deps_failed"),
  63. (_OS_ERROR_TYPES, "os_error"), (_SUBPROCESS_ERROR_TYPES, "subprocess_failed"),
  64. )
  65. # Fixed stop-reason prefixes Hermes itself writes (only the prefix is read, never what follows):
  66. # _update_takeover's preparation failure and update_completion's Windows gateway resume failure.
  67. _STOP_REASON_PREFIX_CLASSES = (
  68. ("historical takeover preparation failed", "deps_failed"), ("Windows gateway recovery failed", "restart_failed"),
  69. )
  70. # An OSError that ended the run, read by its errno token alone (never the text after it):
  71. # ENOSPC (28 on every platform), Windows ERROR_HANDLE_DISK_FULL (39) / ERROR_DISK_FULL (112).
  72. _DISK_FULL_ERRNO = re.compile(r"[A-Z][A-Za-z0-9_]*: \[(?:Errno 28|WinError (?:39|112))\]")
  73. # ---- end iuf c1 ----
  74. # ---- iuf c1 ----
  75. def _fleet_bad(receipt: dict[str, Any]) -> bool:
  76. fleet = receipt.get("fleet")
  77. return isinstance(fleet, list) and any(
  78. isinstance(row, dict) and row.get("state") in _FLEET_BAD_STATES for row in fleet)
  79. def _restart_incomplete(receipt: dict[str, Any]) -> bool:
  80. restart = receipt.get("gateway_restart")
  81. if isinstance(restart, dict) and (
  82. restart.get("incomplete") is True or restart.get("phase_error") or restart.get("failed_units")):
  83. return True
  84. outcomes = receipt.get("runtime_outcomes")
  85. return isinstance(outcomes, list) and any(
  86. isinstance(row, dict) and row.get("outcome") == "failed" for row in outcomes)
  87. def _named_stop(receipt: dict[str, Any], stages: list[dict[str, Any]]) -> str | None:
  88. """The class the run named itself: the user's parked changes on a committed run, or the closed
  89. ``stop_class`` a pre-apply exit recorded (read only while nothing was applied)."""
  90. from .shared_metrics_contract import UPDATE_STOP_CLASSES
  91. if receipt.get("outcome") == "partial" and receipt.get("user_action"):
  92. # Committed; only the user's stashed changes are owed (record_user_action, exit 1). Since C3
  93. # this is the only ``partial`` a receipt gets; older releases' verification wrote it too.
  94. return "local_changes_parked"
  95. stop_class = receipt.get("stop_class")
  96. if stop_class in UPDATE_STOP_CLASSES and not any(s["name"] == "apply" for s in stages):
  97. return stop_class
  98. return None
  99. def update_failure_class(receipt: dict[str, Any], stages: list[dict[str, Any]], outcome: str) -> str:
  100. """Why a failed/refused/partial run stopped, from fields the FINAL receipt already carries.
  101. A pre-apply exit names itself (``stop_class``, recorded on the line before the exit by
  102. update_receipt.record_stop_reason); only a run with no apply mark reads it, so a reason can
  103. never outlive the exit that recorded it. Parked copies (update_receipt._metric_receipt) carry
  104. every field read here except the free text; copies parked by older releases have no ``schema``.
  105. """
  106. if outcome not in {"failed", "refused"}:
  107. return "none"
  108. raw_steps = receipt.get("steps")
  109. steps: list[Any] = raw_steps if isinstance(raw_steps, list) else []
  110. if any(isinstance(s, dict) and s.get("name") == "admission" and not s.get("ok") for s in steps):
  111. return "managed_install"
  112. raw_reason = receipt.get("stop_reason")
  113. reason: str = raw_reason if isinstance(raw_reason, str) else ""
  114. exit_code = receipt.get("exit_code")
  115. match = _EXCEPTION_STOP_REASON.match(reason)
  116. exc_type = match.group(1) if match else ""
  117. if exc_type == "KeyboardInterrupt" or exit_code == 130:
  118. return "interrupted"
  119. if named := _named_stop(receipt, stages):
  120. return named
  121. if outcome == "refused":
  122. # Exit 2 at the command boundary is the updater's refusal convention; on main the only
  123. # open-receipt exit 2 is another updater holding the lock (update_finish).
  124. return "lock_held" if exit_code == 2 else "other"
  125. failed_marks = {s["name"] for s in stages if s.get("outcome") == "failed"}
  126. if "build" in failed_marks:
  127. return "build_failed"
  128. if _fleet_bad(receipt):
  129. return "fleet_stale"
  130. if "restart" in failed_marks or _restart_incomplete(receipt):
  131. return "restart_failed"
  132. if receipt.get("outcome") == "partial":
  133. return "fleet_unverified" # verification failed with no stale/down row and no failed restart
  134. if stages and stages[-1]["name"] == "restart" and stages[-1].get("outcome") == "skipped":
  135. return "restart_failed" # a skipped restart left the fleet owing one (completion exit 1)
  136. if by_reason := next((cls for prefix, cls in _STOP_REASON_PREFIX_CLASSES if reason.startswith(prefix)), None):
  137. return by_reason
  138. if _DISK_FULL_ERRNO.match(reason):
  139. return "disk_full"
  140. if exc_type:
  141. return next((cls for types, cls in _EXCEPTION_TYPE_CLASSES if exc_type in types), "exception")
  142. marked = {s["name"] for s in stages}
  143. if "apply" in marked:
  144. if "deps" not in marked:
  145. return "deps_failed" # the PM preparation child never reached --prepared
  146. if "build" not in marked:
  147. return "build_failed"
  148. return "other"
  149. if "schema" not in receipt:
  150. # A parked copy (update_receipt._metric_receipt): parked only when the checkout already
  151. # moved under the pre-pull interpreter, and it carries no stop reason or exit code.
  152. return "other"
  153. # update_cmd._handle_update_called_process_error is the one finalize("failed") with neither a
  154. # stop reason nor an exit code: a git/installer subprocess failed before the checkout moved.
  155. if not reason and exit_code is None:
  156. return "git_failed"
  157. return "aborted_before_apply"
  158. # ---- end iuf c1 ----
  159. def _epoch(value: Any) -> float | None:
  160. try:
  161. if isinstance(value, (int, float)) and not isinstance(value, bool):
  162. return float(value)
  163. return datetime.fromisoformat(str(value)).timestamp()
  164. except (OverflowError, TypeError, ValueError):
  165. return None
  166. def _elapsed_ms(start: Any, end: Any) -> float | None:
  167. first, last = _epoch(start), _epoch(end)
  168. return None if first is None or last is None or last < first else (last - first) * 1000
  169. def _receipt_stages(receipt: dict[str, Any]) -> list[dict[str, Any]]:
  170. """Stage marks in order, each with a duration since the previous mark (or the run start)."""
  171. from .shared_metrics_contract import UPDATE_STAGES
  172. stages: list[dict[str, Any]] = []
  173. previous = receipt.get("started_at")
  174. for mark in receipt.get("stages") or ():
  175. if not isinstance(mark, dict) or mark.get("name") not in UPDATE_STAGES:
  176. continue
  177. stages.append({**mark, "duration_ms": _elapsed_ms(previous, mark.get("at"))})
  178. previous = mark.get("at") or previous
  179. fleet = receipt.get("fleet")
  180. # The fleet matrix is only passed to finalize by the post-restart verification.
  181. if isinstance(fleet, list) and fleet and not any(s["name"] == "verify" for s in stages):
  182. # ---- iuf c1 ----
  183. # ``partial`` is written only by update_cmd_fleet._verify_fleet_after_update, which also
  184. # writes it for a failed build or restart; with no failed stage mark, verification itself
  185. # failed even when every fleet row reads current (zero rows expected, an unaccounted
  186. # runtime, a dashboard that did not come back, a Windows resume failure).
  187. bad = _fleet_bad(receipt) or (
  188. receipt.get("outcome") == "partial" and not any(s.get("outcome") == "failed" for s in stages))
  189. # ---- end iuf c1 ----
  190. stages.append({
  191. "name": "verify", "outcome": "failed" if bad else "success",
  192. "duration_ms": _elapsed_ms(previous, receipt.get("finished_at")),
  193. })
  194. return stages
  195. def _failed_stage(stages: list[dict[str, Any]]) -> str:
  196. """Where a failed/refused run stopped: the failing stage, else the stage it never reached."""
  197. from .shared_metrics_contract import UPDATE_STAGE_ORDER
  198. if not stages:
  199. return "other"
  200. last = stages[-1]
  201. terminal = last["name"] == "verify" or (last["name"] == "restart" and last.get("outcome") == "skipped")
  202. if last.get("outcome") == "failed" or terminal:
  203. failed = [s["name"] for s in stages if s.get("outcome") == "failed"]
  204. # ---- iuf c1 ----
  205. # A failed run whose last mark is a skipped restart failed AT the restart: the completion
  206. # exits 1 when a skipped restart leaves the fleet owing one, or the Windows resume fails.
  207. return failed[-1] if failed else last["name"]
  208. # ---- end iuf c1 ----
  209. index = UPDATE_STAGE_ORDER.index(last["name"])
  210. return UPDATE_STAGE_ORDER[index + 1] if index + 1 < len(UPDATE_STAGE_ORDER) else "other"
  211. def _apply_mode(receipt: dict[str, Any], stages: list[dict[str, Any]]) -> str:
  212. for stage in stages:
  213. if stage["name"] == "apply" and stage.get("mode") in {"git", "zip"}:
  214. return stage["mode"]
  215. # An admission refusal means the install is owned by something else (Docker, Nix, a package).
  216. if any(isinstance(s, dict) and s.get("name") == "admission" and not s.get("ok") for s in receipt.get("steps") or ()):
  217. return "external"
  218. return "unknown"
  219. def _committed_with_work_owed(receipt: dict[str, Any]) -> bool:
  220. """The code moved (an apply mark that did not fail), and the run closed owing work, not failed:
  221. interrupted after the commit point (finalize_interrupted_update_receipt) or the user's parked
  222. changes (record_user_action -> ``partial``). Follow-ups alone already finalize ``success`` (C3)."""
  223. applied = any(isinstance(mark, dict) and mark.get("name") == "apply" and mark.get("outcome") != "failed"
  224. for mark in receipt.get("stages") or ())
  225. owed = receipt.get("outcome") == "interrupted" or (
  226. receipt.get("outcome") == "partial" and bool(receipt.get("user_action")))
  227. return applied and owed
  228. def update_receipt_fields(receipt: dict[str, Any]) -> tuple[dict[str, str], list[dict[str, str]]] | None:
  229. """Bounded hermes.update.run + hermes.update.stage dimensions for one FINAL receipt."""
  230. from .shared_metrics_contract import update_duration_bucket, version_age_bucket
  231. if not isinstance(receipt, dict) or not receipt.get("finished_at"):
  232. return None
  233. stages = _receipt_stages(receipt)
  234. outcome = _RUN_OUTCOMES.get(str(receipt.get("outcome") or ""), "failed")
  235. if outcome == "success" and any(s["name"] == "apply" and s.get("outcome") == "skipped" for s in stages):
  236. outcome = "noop"
  237. if _committed_with_work_owed(receipt):
  238. outcome = "partial"
  239. started = _epoch(receipt.get("started_at"))
  240. committed = _epoch((receipt.get("pre_update") or {}).get("commit_date"))
  241. age_ms = None if started is None or committed is None else (started - committed) * 1000
  242. failure_class = update_failure_class(receipt, stages, "failed" if outcome == "partial" else outcome)
  243. run = {
  244. "apply_mode": _apply_mode(receipt, stages),
  245. "duration_bucket": update_duration_bucket(_elapsed_ms(receipt.get("started_at"), receipt.get("finished_at"))),
  246. "failed_stage": (
  247. # The parked autostash is the apply's last step (update_cmd._pull_updates restores it).
  248. "apply" if failure_class == "local_changes_parked"
  249. else _failed_stage(stages) if outcome in {"failed", "refused", "partial"} else "none"),
  250. "from_version_age_bucket": version_age_bucket(age_ms),
  251. "kind": "desktop" if receipt.get("initiator") == "desktop" else "cli",
  252. "outcome": outcome,
  253. # ---- iuf c1 ----
  254. "failure_class": failure_class,
  255. # ---- end iuf c1 ----
  256. }
  257. if run["outcome"] == "refused" and not stages:
  258. run["failed_stage"] = "none"
  259. stage_rows = [
  260. {
  261. "duration_bucket": update_duration_bucket(stage["duration_ms"]),
  262. "outcome": stage.get("outcome") if stage.get("outcome") in {"success", "failed", "skipped"} else "failed",
  263. "stage": stage["name"],
  264. }
  265. for stage in stages
  266. ]
  267. if died_in := _unmarked_failed_stage(run, stages):
  268. last_mark = next((s["at"] for s in reversed(stages) if s.get("at")), receipt.get("started_at"))
  269. stage_rows.append({
  270. "duration_bucket": update_duration_bucket(_elapsed_ms(last_mark, receipt.get("finished_at"))),
  271. "outcome": "failed", "stage": died_in,
  272. })
  273. return run, stage_rows
  274. def _unmarked_failed_stage(run: dict[str, str], stages: list[dict[str, Any]]) -> str | None:
  275. """The stage a failed run stopped in when the receipt holds no mark for it, else None.
  276. Stage marks are END marks, so a run that exits inside a stage (every pre-apply ``sys.exit``:
  277. fetch, channel, branch, merge, HEAD checks) leaves none for it and the stage rows would show no
  278. failure where the run row says it died. Only ``failed`` runs: a refusal is not a stage failure,
  279. and a committed run that owes follow-ups is a ``success`` whose failed stage already has its mark.
  280. """
  281. from .shared_metrics_contract import UPDATE_STAGES
  282. died_in = run["failed_stage"]
  283. if run["outcome"] != "failed" or died_in not in UPDATE_STAGES or any(s["name"] == died_in for s in stages):
  284. return None
  285. return died_in
  286. def _collection_on() -> bool:
  287. """Cheap pre-gate so a disabled install never loads the Relay runtime; `_emit` re-checks."""
  288. from hermes_cli.config import read_raw_config_readonly
  289. config: Any = read_raw_config_readonly() or {}
  290. for key in ("telemetry", "shared_metrics"):
  291. config = config.get(key) if isinstance(config, dict) else None
  292. return isinstance(config, dict) and config.get("enabled") is True
  293. def _claim_update_id(update_id: Any) -> tuple[bool, Path | None]:
  294. """``(first, latch)``: first is False when this profile already counted ``update_id``."""
  295. from hermes_constants import get_hermes_home
  296. if not isinstance(update_id, str) or not _UPDATE_ID.fullmatch(update_id):
  297. return True, None # nothing stable to dedupe on
  298. directory = get_hermes_home() / "telemetry" / "shared_metrics" / RECORDED_DIRNAME
  299. directory.mkdir(parents=True, exist_ok=True)
  300. latch = directory / update_id
  301. try:
  302. os.close(os.open(latch, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
  303. except FileExistsError:
  304. return False, None
  305. try:
  306. for stale in sorted(directory.iterdir(), key=lambda p: p.stat().st_mtime, reverse=True)[_RECORDED_KEEP:]:
  307. stale.unlink(missing_ok=True)
  308. except OSError: # a concurrent prune won; the next claim prunes again
  309. pass
  310. return True, latch
  311. def record_update_receipt(receipt: dict[str, Any], *, wait_saved: bool = False) -> bool:
  312. """Record one run row plus its stage rows from a final receipt, once per update_id.
  313. ``wait_saved`` (parked receipts) blocks until the rows are in the store; False means the caller
  314. must keep the receipt for a later retry. True also covers "nothing to record". Never raises.
  315. """
  316. try:
  317. if not _collection_on():
  318. return True
  319. from . import shared_metrics_contract as contract
  320. from .shared_metrics_events import _emit, emit_saved
  321. derived = update_receipt_fields(receipt)
  322. if derived is None:
  323. return True
  324. first, latch = _claim_update_id(receipt.get("update_id"))
  325. if not first:
  326. return True
  327. run, stage_rows = derived
  328. rows = [(contract.UPDATE_RUN_MARK, run), *((contract.UPDATE_STAGE_MARK, row) for row in stage_rows)]
  329. if not wait_saved:
  330. for mark, row in rows:
  331. _emit(mark, lambda row=row: row)
  332. return True
  333. if emit_saved(rows):
  334. return True # even partly: a retry would count again the rows that did land
  335. if latch is not None:
  336. latch.unlink(missing_ok=True) # nothing landed: let the retry count it
  337. return False
  338. except Exception:
  339. logger.debug("Update shared metrics not recorded", exc_info=True)
  340. return False
  341. def pending_updates_dir(home: Path) -> Path:
  342. return home / "telemetry" / "shared_metrics" / PENDING_DIRNAME
  343. def purge_pending_updates(home: Path) -> None:
  344. shutil.rmtree(pending_updates_dir(home), ignore_errors=True)
  345. def report_pending_updates() -> None:
  346. """Record receipts a pre-pull interpreter parked (it must not import pulled code). Never raises."""
  347. try:
  348. from hermes_constants import get_hermes_home
  349. from .shared_metrics_process import _claim, settle_claim
  350. directory = pending_updates_dir(get_hermes_home())
  351. if not directory.is_dir():
  352. return
  353. for path in sorted(directory.iterdir()):
  354. if path.name.startswith(".") or ".json" not in path.name:
  355. continue
  356. claimed = _claim(path) # a concurrent start that loses the rename records nothing
  357. if claimed is None:
  358. continue
  359. try:
  360. receipt = json.loads(claimed.read_text(encoding="utf-8-sig"))
  361. except (OSError, ValueError):
  362. receipt = None
  363. saved = not isinstance(receipt, dict) or record_update_receipt(receipt, wait_saved=True)
  364. settle_claim(claimed, path, saved)
  365. except Exception:
  366. logger.debug("Pending update shared metrics not reported", exc_info=True)
  367. def desktop_update_fields(
  368. *, outcome: Any, failed_stage: Any, duration_ms: Any, mechanism: Any, from_commit_date: Any = None,
  369. ) -> dict[str, str]:
  370. """hermes.update.run dims for a Desktop packaged self-update (RPC-reported)."""
  371. from .shared_metrics_contract import (
  372. DESKTOP_UPDATE_STAGES, UPDATE_OUTCOMES, update_duration_bucket, version_age_bucket,
  373. )
  374. outcome_value = str(outcome or "").strip().lower()
  375. outcome_value = outcome_value if outcome_value in UPDATE_OUTCOMES else "failed"
  376. stage = str(failed_stage or "").strip().lower()
  377. commit = _epoch(from_commit_date)
  378. # Desktop sends seconds since epoch (install stamp commitDate); age is measured now.
  379. age_ms = None if commit is None else (time.time() - commit) * 1000
  380. return {
  381. "apply_mode": _DESKTOP_APPLY_MODES.get(str(mechanism or "").strip().lower(), "unknown"),
  382. "duration_bucket": update_duration_bucket(duration_ms),
  383. "failed_stage": (stage if stage in DESKTOP_UPDATE_STAGES else "other") if outcome_value == "failed" else "none",
  384. "from_version_age_bucket": version_age_bucket(age_ms),
  385. "kind": "desktop",
  386. "outcome": outcome_value,
  387. # ---- iuf c1 ----
  388. # The Desktop RPC carries a stage, never a reason.
  389. "failure_class": "unknown" if outcome_value in {"failed", "refused"} else "none",
  390. # ---- end iuf c1 ----
  391. }
  392. def record_desktop_update(**raw: Any) -> None:
  393. """Emit one Desktop self-update run through the enabled() gate. Never raises."""
  394. from . import shared_metrics_contract as contract
  395. from .shared_metrics_events import _emit
  396. _emit(contract.UPDATE_RUN_MARK, desktop_update_fields, **raw)