fix(gateway): retract a removed setting's bridge leftover before env overrides read it
4c13c06 (#154562) moved the outer yaml_env_refresh() up to load_gateway_config() so a load
that fails in typed construction rolls its bridged writes back. The nested refresh in
load_yaml_layer() then only participated, so retraction of unchanged bridge-owned
leftovers moved to the outer exit, after GatewayConfig.from_dict and _apply_env_overrides.
A restart child that inherited TELEGRAM_REPLY_TO_MODE / DISCORD_REPLY_TO_MODE (plus marker)
for a key since removed from config.yaml built its first config with the stale value.
Split the two roles: yaml_env_transaction() is the rollback scope held across the whole
load; yaml_env_refresh() (the YAML layer) commits the retraction at its own end, before
anything reads the env. Each retracted value's prior is recorded first, so a load that
later raises restores it along with its writes. A bare yaml_env_transaction() with no
layer inside still retracts at exit, as the old single scope did.
This commit is contained in:
@@ -856,14 +856,14 @@ def load_gateway_config(*, strict: bool = False) -> GatewayConfig:
|
||||
``strict=True`` raises a config.yaml failure instead of falling back to env + gateway.json: a live
|
||||
allowlist refresh keeps its last good lists rather than apply an env-only config."""
|
||||
from gateway import config_loader
|
||||
from gateway.platforms._shared import gate_config_version, yaml_env_refresh
|
||||
from gateway.platforms._shared import gate_config_version, yaml_env_transaction
|
||||
|
||||
_home = get_hermes_home()
|
||||
version = gate_config_version()
|
||||
gw_data = config_loader.load_legacy_gateway_json(_home)
|
||||
# One transaction through typed construction, overrides and validation: the runner's authorization
|
||||
# reads the bridged env, so a load that fails after the YAML overlay must not leave its writes.
|
||||
with yaml_env_refresh():
|
||||
with yaml_env_transaction():
|
||||
config = _load_gateway_config_layers(_home, gw_data, strict)
|
||||
for platform_config in config.platforms.values():
|
||||
platform_config.loaded_version = version
|
||||
|
||||
@@ -213,6 +213,23 @@ class _YamlEnvLoad:
|
||||
# adapter (last good lists) and the runner (process env) never check different policies.
|
||||
prior: dict[str, tuple[Optional[str], Optional[str]]] = field(default_factory=dict)
|
||||
undo: list[Callable[[], None]] = field(default_factory=list) # ownership state kept outside the env
|
||||
before: dict[str, str] = field(default_factory=dict) # bridge markers present when the load began
|
||||
in_layer: bool = False
|
||||
committed: bool = False
|
||||
|
||||
def retract_leftovers(self) -> None:
|
||||
"""Drop unchanged bridge-owned values this load's YAML no longer sets. Their priors are
|
||||
recorded first, so a later failure in the same load restores them with its writes."""
|
||||
self.committed = True
|
||||
if self.failed:
|
||||
return
|
||||
for name, digest in self.before.items():
|
||||
marker = bridged_env_marker(name)
|
||||
if (name not in self.seen and os.getenv(marker) == digest
|
||||
and _is_bridge_leftover(name, digest) and not _supplied_by_operator(name)):
|
||||
self.prior.setdefault(name, (os.getenv(name), digest))
|
||||
os.environ.pop(name, None)
|
||||
os.environ.pop(marker, None)
|
||||
|
||||
def restore(self) -> None:
|
||||
for name, values in self.prior.items():
|
||||
@@ -250,8 +267,12 @@ def abort_yaml_env_refresh() -> None:
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def yaml_env_refresh():
|
||||
"""Retract only unchanged bridge-owned leftovers after one complete, successful YAML load."""
|
||||
def yaml_env_transaction():
|
||||
"""One load's rollback scope: everything bridged or retracted inside it is restored if it raises.
|
||||
|
||||
``load_gateway_config`` holds it across typed construction and env overrides, so a load that fails
|
||||
after the YAML layer publishes nothing; the retraction itself happens at the YAML layer's end
|
||||
(:func:`yaml_env_refresh`), before anything reads the env it cleans."""
|
||||
if bridge_env_skipped():
|
||||
yield
|
||||
return
|
||||
@@ -259,9 +280,9 @@ def yaml_env_refresh():
|
||||
if getattr(_YAML_ENV_LOAD, "current", None) is not None:
|
||||
yield # A nested load participates in the outer load, never clears its partial writes.
|
||||
return
|
||||
before = {key[len(BRIDGED_ENV_MARKER_PREFIX):]: value for key, value in os.environ.items()
|
||||
if key.startswith(BRIDGED_ENV_MARKER_PREFIX) and key != BRIDGED_ENV_MARKER_PREFIX}
|
||||
load = _YamlEnvLoad()
|
||||
load = _YamlEnvLoad(before={
|
||||
key[len(BRIDGED_ENV_MARKER_PREFIX):]: value for key, value in os.environ.items()
|
||||
if key.startswith(BRIDGED_ENV_MARKER_PREFIX) and key != BRIDGED_ENV_MARKER_PREFIX})
|
||||
_YAML_ENV_LOAD.current = load
|
||||
try:
|
||||
try:
|
||||
@@ -269,17 +290,32 @@ def yaml_env_refresh():
|
||||
except BaseException:
|
||||
load.restore()
|
||||
raise
|
||||
if not load.failed:
|
||||
for name, digest in before.items():
|
||||
marker = bridged_env_marker(name)
|
||||
if (name not in load.seen and os.getenv(marker) == digest
|
||||
and _is_bridge_leftover(name, digest) and not _supplied_by_operator(name)):
|
||||
os.environ.pop(name, None)
|
||||
os.environ.pop(marker, None)
|
||||
if not load.committed:
|
||||
load.retract_leftovers()
|
||||
finally:
|
||||
del _YAML_ENV_LOAD.current
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def yaml_env_refresh():
|
||||
"""The YAML layer: retract only unchanged bridge-owned leftovers after one complete, successful
|
||||
overlay, before the caller builds a config from the env (env overrides read the same names)."""
|
||||
if bridge_env_skipped():
|
||||
yield
|
||||
return
|
||||
with yaml_env_transaction(), _YAML_ENV_LOCK:
|
||||
load = _YAML_ENV_LOAD.current
|
||||
if load.in_layer or load.committed:
|
||||
yield # a nested or later layer: only the transaction's first layer decides retraction
|
||||
return
|
||||
load.in_layer = True
|
||||
try:
|
||||
yield
|
||||
load.retract_leftovers()
|
||||
finally:
|
||||
load.in_layer = False
|
||||
|
||||
|
||||
def record_yaml_env_prior(name: str, undo: Callable[[], None]) -> None:
|
||||
"""Record *name* before a bridge writes it outside :func:`yaml_env_setter` (the allow-all grant),
|
||||
so a load that raises restores it and runs *undo* to roll back that writer's ownership flag."""
|
||||
|
||||
@@ -94,3 +94,22 @@ def test_a_non_strict_load_that_fails_mid_bridge_restores_the_last_good_env(home
|
||||
_write(home, {"discord": {"allow_from": ["222"]}, "require_mention": True, "telegram": True})
|
||||
load_gateway_config()
|
||||
assert {name: (os.environ.get(name), os.environ.get(bridged_env_marker(name))) for name in good} == good
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform,var", [(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"),
|
||||
(Platform.DISCORD, "DISCORD_REPLY_TO_MODE")])
|
||||
def test_a_removed_setting_leftover_never_shapes_the_load_that_retracts_it(home, monkeypatch, platform, var):
|
||||
"""A restart child inherits a bridged value whose YAML key was since removed: the env-override pass
|
||||
of the same load must not read it, and a load that then fails restores it with the last good env."""
|
||||
from gateway.platforms._shared import bridged_env_digest, bridged_env_marker
|
||||
|
||||
monkeypatch.setenv(var, "all")
|
||||
monkeypatch.setenv(bridged_env_marker(var), bridged_env_digest("all"))
|
||||
broken = {"enabled": True, "home_channel": {"name": "x"}} # fails typed construction after the YAML layer
|
||||
_write(home, {"platforms": {platform.value: broken}})
|
||||
with pytest.raises(Exception):
|
||||
load_gateway_config()
|
||||
assert (os.environ.get(var), os.environ.get(bridged_env_marker(var))) == ("all", bridged_env_digest("all"))
|
||||
_write(home, {"platforms": {platform.value: {"enabled": True}}})
|
||||
assert load_gateway_config().platforms[platform].reply_to_mode != "all"
|
||||
assert var not in os.environ and bridged_env_marker(var) not in os.environ
|
||||
|
||||
Reference in New Issue
Block a user