The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(webhook): drop dead revision snapshot, lock-free reads, CAS owns the disable rule
kshitijk4poored7909bad983
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex 3042040b7de..17fa5f542f6 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -410,13 +410,23 @@ class WebhookAdapter(BasePlatformAdapter):logger.debug("[webhook] Dynamic subscriptions file removed, cleared dynamic routes")self._dynamic_routes_stat = Nonereturn+ stat_key = (st.st_mtime_ns, st.st_size, st.st_ino)+ if stat_key == self._dynamic_routes_stat:+ return # No changetry:- stat_key = (st.st_mtime_ns, st.st_size, st.st_ino)- if stat_key == self._dynamic_routes_stat:- return # No changedata = json.loads(subs_path.read_text(encoding="utf-8-sig"))- if not isinstance(data, dict):- return # keep the last good snapshot+ except ValueError as e:+ # Keep the last good snapshot, and remember this version so it is parsed once, not per POST.+ self._dynamic_routes_stat = stat_key+ logger.error("[webhook] Failed to parse dynamic routes: %s", e)+ return+ except OSError as e:+ logger.error("[webhook] Failed to read dynamic routes: %s", e)+ return+ if not isinstance(data, dict):+ self._dynamic_routes_stat = stat_key # keep the last good snapshot; parse this version once+ return+ try:self._dynamic_routes = { # static routes take precedencek: v for k, v in data.items()if isinstance(v, dict) and k not in self._static_routes and self._dynamic_route_allowed(k, v)diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.pyindex d14660894e3..83f3fb20cc6 100644--- a/hermes_cli/web_routers/ops.py+++ b/hermes_cli/web_routers/ops.py@@ -230,15 +230,13 @@ async def create_webhook(body: WebhookCreate, profile: Optional[str] = None):route["deliver_only"] = Trueif body.deliver_chat_id:route["deliver_extra"] = {"chat_id": body.deliver_chat_id}- if isinstance(expected, dict) and expected.get("enabled") is False:- route["enabled"] = Falsedef _save():try:- wh._replace_subscription(name, route, expected)+ published = wh._replace_subscription(name, route, expected)except wh.SubscriptionMutationConflict as exc:raise HTTPException(status_code=409, detail=str(exc)) from exc- return _webhook_route_summary(name, route, wh._get_webhook_base_url())+ return _webhook_route_summary(name, published, wh._get_webhook_base_url())summary = await config_scoped_to_thread(profile, _save)summary["secret"] = secret # surfaced exactly once, on creatediff --git a/hermes_cli/webhook.py b/hermes_cli/webhook.pyindex 11a92ff7b43..e76230a6383 100644--- a/hermes_cli/webhook.py+++ b/hermes_cli/webhook.py@@ -20,7 +20,7 @@ from hermes_cli.config import cfg_get_SUBSCRIPTIONS_FILENAME = "webhook_subscriptions.json"_SUBSCRIPTIONS_FILE_MODE = 0o600_SUBSCRIPTIONS_LOCK_FILENAME = ".webhook_subscriptions.lock"-_SUBSCRIPTIONS_THREAD_LOCK = threading.RLock()+_SUBSCRIPTIONS_THREAD_LOCK = threading.Lock()_MISSING_SUBSCRIPTION = object()@@ -47,31 +47,23 @@ def _subscriptions_lock():yield-def _load_subscriptions_unlocked() -> tuple[Dict[str, dict], str | None]:- """Return one file snapshot and its content revision. Caller holds the store lock."""- path = _subscriptions_path()+def _load_subscriptions_unlocked() -> Dict[str, dict]:+ """Read one complete store snapshot; unreadable or malformed files read as empty."""try:- raw = path.read_bytes()- except FileNotFoundError:- return {}, None- except Exception:- return {}, None- revision = hashlib.sha256(raw).hexdigest()+ raw = _subscriptions_path().read_bytes()+ except OSError:+ return {}try:data = json.loads(raw.decode("utf-8-sig"))- return (data if isinstance(data, dict) else {}), revision- except Exception:- return {}, revision---def _load_subscriptions_snapshot() -> tuple[Dict[str, dict], str | None]:- """Read a coherent store snapshot; the revision changes with the file content."""- with _subscriptions_lock():- return _load_subscriptions_unlocked()+ except ValueError:+ return {}+ return data if isinstance(data, dict) else {}def _load_subscriptions() -> Dict[str, dict]:- return _load_subscriptions_snapshot()[0]+ """Lock-free read: writers publish by atomic rename, so a reader always sees one whole+ snapshot, and read-only homes (no lock file can be created) keep working."""+ return _load_subscriptions_unlocked()def _save_subscriptions_unlocked(subs: Dict[str, dict]) -> None:@@ -80,24 +72,23 @@ def _save_subscriptions_unlocked(subs: Dict[str, dict]) -> None:atomic_json_write(_subscriptions_path(), subs, mode=_SUBSCRIPTIONS_FILE_MODE)-def _save_subscriptions(subs: Dict[str, dict]) -> None:- """Replace the whole store under its writer lock."""- with _subscriptions_lock():- _save_subscriptions_unlocked(subs)--def _mutate_subscriptions(mutate: Callable[[Dict[str, dict]], Any]) -> Any:"""Lock, re-read, mutate and atomically publish one complete store snapshot."""with _subscriptions_lock():- subscriptions, _ = _load_subscriptions_unlocked()+ subscriptions = _load_subscriptions_unlocked()result = mutate(subscriptions)_save_subscriptions_unlocked(subscriptions)return result-def _replace_subscription(name: str, route: dict, expected: object) -> None:- """CAS one route so a stale update cannot recreate a removed or disabled record."""- def replace(subscriptions: Dict[str, dict]) -> None:+def _replace_subscription(name: str, route: dict, expected: object) -> dict:+ """CAS one route so a stale update cannot recreate a removed or disabled record.++ A general update is not an enable operation: an explicit ``enabled: False`` on the+ replaced record survives (only the dashboard's dedicated enabled endpoint lifts it).+ Returns the route as published.+ """+ def replace(subscriptions: Dict[str, dict]) -> dict:current = subscriptions.get(name, _MISSING_SUBSCRIPTION)expected_missing = expected is _MISSING_SUBSCRIPTIONif (current is _MISSING_SUBSCRIPTION) != expected_missing or (@@ -106,9 +97,13 @@ def _replace_subscription(name: str, route: dict, expected: object) -> None:raise SubscriptionMutationConflict(f"Webhook subscription '{name}' changed concurrently; retry the operation.")- subscriptions[name] = route+ published = route+ if isinstance(current, dict) and current.get("enabled") is False:+ published = {**route, "enabled": False}+ subscriptions[name] = published+ return published- _mutate_subscriptions(replace)+ return _mutate_subscriptions(replace)def _get_webhook_config() -> dict:@@ -212,11 +207,7 @@ def _cmd_subscribe(args):"Omit --secret to generate one automatically, or provide a different secret.")return- secret = (- (args.secret or secrets.token_urlsafe(32))- if profile_changed- else (args.secret or existing.get("secret") or secrets.token_urlsafe(32))- )+ secret = args.secret or (None if profile_changed else existing.get("secret")) or secrets.token_urlsafe(32)events = [e.strip() for e in args.events.split(",")] if args.events else []route = {"description": args.description or f"Agent-created subscription: {name}",@@ -227,10 +218,6 @@ def _cmd_subscribe(args):"deliver": args.deliver or "log","profile": profile,"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}- # A general subscription update is not an enable operation. Preserve an explicit revocation;- # only the dashboard's dedicated enabled endpoint may lift it.- if existing.get("enabled") is False:- route["enabled"] = Falseif getattr(args, "deliver_only", False):if getattr(args, "cron_job", ""):@@ -268,7 +255,7 @@ def _cmd_subscribe(args):if args.deliver_chat_id:route["deliver_extra"] = {"chat_id": args.deliver_chat_id}try:- _replace_subscription(name, route, expected)+ route = _replace_subscription(name, route, expected)except SubscriptionMutationConflict as exc:print(f"Error: {exc}")returndiff --git a/tests/hermes_cli/test_webhook_cli.py b/tests/hermes_cli/test_webhook_cli.pyindex 1fc88cff0bf..d70f6c3d6a9 100644--- a/tests/hermes_cli/test_webhook_cli.py+++ b/tests/hermes_cli/test_webhook_cli.py@@ -11,7 +11,7 @@ from hermes_cli.webhook import (webhook_command,_get_webhook_base_url,_load_subscriptions,- _save_subscriptions,+ _mutate_subscriptions,_subscriptions_path,)@@ -264,7 +264,7 @@ class TestPersistence:def test_save_creates_secret_file_owner_only_under_permissive_umask(self):old_umask = os.umask(0o022)try:- _save_subscriptions({"demo": {"secret": "TOPSECRET", "prompt": "x"}})+ _mutate_subscriptions(lambda s: s.update(demo={"secret": "TOPSECRET", "prompt": "x"}))finally:os.umask(old_umask)@@ -280,7 +280,7 @@ class TestPersistence:path.write_text(json.dumps({"old": {"secret": "stale", "prompt": "x"}}))path.chmod(0o644)- _save_subscriptions({"demo": {"secret": "FRESH", "prompt": "x"}})+ _mutate_subscriptions(lambda s: s.update(demo={"secret": "FRESH", "prompt": "x"}))assert stat.S_IMODE(path.stat().st_mode) == 0o600assert "FRESH" in path.read_text(encoding="utf-8")diff --git a/website/docs/user-guide/messaging/webhooks.md b/website/docs/user-guide/messaging/webhooks.mdindex 64ea65a8aae..b53b6a08166 100644--- a/website/docs/user-guide/messaging/webhooks.md+++ b/website/docs/user-guide/messaging/webhooks.md@@ -530,7 +530,7 @@ hermes webhook test github-issues --payload '{"issue": {"number": 42, "title": "### How dynamic subscriptions work- Subscriptions are stored in `~/.hermes/webhook_subscriptions.json`-- The webhook adapter hot-reloads a coherent snapshot of this file on each incoming request (content-revision-gated)+- The webhook adapter hot-reloads a coherent snapshot of this file on each incoming request (stat-gated (mtime/size/inode), lock-free)- Static routes from `config.yaml` always take precedence over dynamic ones with the same name- Dynamic subscriptions use the same route format and capabilities as static routes (events, prompt templates, skills, delivery)- Create, update, enable/disable, and remove operations are serialized and atomically replace the store; a stale concurrent update is rejected rather than restoring a route another operation removed or disabled