Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(config): cross-process write transaction for narrow field writers (#1465)

Call White4302de75c8d0
diff --git a/config/v2_config.py b/config/v2_config.py
index 2589c1e76..68e564204 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -162,6 +162,56 @@ def _memory_config_transaction(config_path: Path) -> Iterator[None]:
os.close(descriptor)
+@contextmanager
+def config_write_transaction(config_path: Optional[Path] = None) -> Iterator["V2Config"]:
+ """Cross-process read-modify-write transaction for ``config.json`` (#1458).
+
+ Generalizes the Memory transaction: the same file lock serializes the
+ WHOLE load→mutate→save cycle, so the mutator always sees a snapshot
+ loaded inside the transaction and cannot revert a concurrent writer's
+ fields (the stale-snapshot race ``CONFIG_LOCK`` cannot fix because it
+ is process-local while the UI API and controller are separate
+ processes). Lock order and re-entrancy match the Memory transaction:
+ ``CONFIG_LOCK`` first, then the file lock; nested acquisitions
+ re-enter the process lock only.
+
+ Yields a freshly loaded ``V2Config``; mutate it in place and it is
+ saved on clean context exit. Mutator exceptions abort with no write.
+ """
+
+ from config import paths as _paths
+
+ path = config_path or _paths.get_config_path()
+ with _memory_config_transaction(path):
+ try:
+ config = V2Config.load(path)
+ except FileNotFoundError:
+ config = V2Config.default()
+ yield config
+ config.save(path)
+
+
+def update_config_fields(
+ mutator: Callable[["V2Config"], None],
+ *,
+ config_path: Optional[Path] = None,
+) -> "V2Config":
+ """Apply ``mutator`` to a fresh config under the cross-process lock.
+
+ The preferred shape for narrow field writers (relay marker, language,
+ default provider, secrets rotation): decisions are made before the
+ call, the mutator only assigns fields, and the transaction guarantees
+ neither snapshot staleness nor lost updates. Direct
+ ``V2Config.load`` → mutate → ``save()`` pairs outside a transaction
+ are a defect for cross-process state (see docs/plans/
+ config-cross-process-write-serialization.md).
+ """
+
+ with config_write_transaction(config_path) as config:
+ mutator(config)
+ return config
+
+
_MODEL_HUB_CREDENTIAL_PATTERNS = (
re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),
re.compile(
diff --git a/core/controller.py b/core/controller.py
index 39af04d9a..5ac21038a 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1171,11 +1171,9 @@ class Controller:
counts,
)
- from config.v2_config import V2Config
+ from config.v2_config import update_config_fields
- v2_config = V2Config.load()
- v2_config.language = chosen
- v2_config.save()
+ update_config_fields(lambda cfg: setattr(cfg, "language", chosen))
self.config.language = chosen
logger.info("Migrated legacy per-channel language to global config: %s", chosen)
except Exception as err:
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 1d0519a3f..ec13a6dae 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -706,11 +706,9 @@ class SettingsHandler(BaseHandler):
language_saved = True
if language is not None and language != self.config.language:
try:
- from config.v2_config import V2Config
+ from config.v2_config import update_config_fields
- v2_config = V2Config.load()
- v2_config.language = language
- v2_config.save()
+ update_config_fields(lambda cfg: setattr(cfg, "language", language))
self.config.language = language
except Exception as err:
language_saved = False
diff --git a/tests/test_config_write_transaction.py b/tests/test_config_write_transaction.py
new file mode 100644
index 000000000..709f8e038
--- /dev/null
+++ b/tests/test_config_write_transaction.py
@@ -0,0 +1,166 @@
+"""Tests for the cross-process config write transaction (#1458).
+
+Pins two contracts:
+
+- ``update_config_fields`` performs its load INSIDE the file lock, so a
+ concurrent writer's committed fields survive a later save — the
+ stale-snapshot race that ``CONFIG_LOCK`` cannot fix across processes.
+- Direct ``load → mutate → save`` pairs outside the transaction DO lose
+ interleaved writes; the test asserts the race shape itself so the
+ primitive's value stays grounded in a failing baseline.
+
+Cross-process behavior is exercised through the same flock every
+production writer takes (threads + the real file lock; separate OS
+processes would only add scheduling noise the lock already excludes).
+"""
+
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from config.v2_config import V2Config, update_config_fields
+
+
+def isolated_config_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ V2Config.default().save()
+ return paths.get_config_path()
+
+
+def test_update_config_fields_writes_and_returns_fresh_state(
+ isolated_config_home: Path,
+) -> None:
+ updated = update_config_fields(lambda cfg: setattr(cfg, "language", "zh"))
+ assert updated.language == "zh"
+ assert V2Config.load().language == "zh"
+
+
+def _txn_worker_a(home: str, entered: threading.Event, release: threading.Event) -> None:
+ """Hold the transaction open (file lock held) until released."""
+ import os as _os
+
+ _os.environ["AVIBE_HOME"] = home
+ from config.v2_config import update_config_fields
+
+ def mutator(cfg: V2Config) -> None:
+ cfg.language = "zh"
+ entered.set()
+ assert release.wait(timeout=15), "worker A never released"
+
+ update_config_fields(mutator)
+
+
+def _txn_worker_b(home: str, attempted: threading.Event, done: threading.Event, saw_queue) -> None:
+ import os as _os
+
+ _os.environ["AVIBE_HOME"] = home
+ from config.v2_config import update_config_fields
+
+ def mutator(cfg: V2Config) -> None:
+ saw_queue.put(cfg.language)
+ cfg.runtime.log_level = "DEBUG"
+
+ # Signal AFTER imports/setup but BEFORE the transaction: the parent
+ # waits for this before concluding anything about lock blocking, so
+ # a slow spawn/import on a loaded CI host cannot fake the
+ # "B never attempted entry" outcome.
+ attempted.set()
+ update_config_fields(mutator)
+ done.set()
+
+
+def test_transaction_blocks_second_process_until_first_releases(
+ isolated_config_home: Path,
+) -> None:
+ """The cross-process contract, exercised across REAL processes:
+ while worker A sits inside its transaction (file lock held), worker
+ B's transaction must not enter — and once A releases, B's mutator
+ sees A's committed field. Thread-based variants of this test are
+ vacuous: the process-local ``CONFIG_LOCK`` serializes them before
+ the file lock, so they would pass even with a no-op flock."""
+
+ import multiprocessing as mp
+
+ ctx = mp.get_context("spawn")
+ entered = ctx.Event()
+ release = ctx.Event()
+ b_attempted = ctx.Event()
+ b_done = ctx.Event()
+ saw_queue = ctx.Queue()
+
+ a = ctx.Process(target=_txn_worker_a, args=(str(isolated_config_home.parent.parent), entered, release))
+ b = ctx.Process(
+ target=_txn_worker_b,
+ args=(str(isolated_config_home.parent.parent), b_attempted, b_done, saw_queue),
+ )
+ a.start()
+ assert entered.wait(timeout=15), "worker A never entered its transaction"
+ b.start()
+ # B has reached the transaction call (imports done); from here the
+ # only thing between it and completion is the file lock.
+ assert b_attempted.wait(timeout=15), "worker B never reached the transaction"
+ # B must be blocked on the file lock while A holds it. Generous
+ # margin: an unblocked trivial transaction finishes well inside it.
+ assert not b_done.wait(timeout=1.0), "B entered the transaction while A held the file lock"
+ release.set()
+ a.join(timeout=15)
+ b.join(timeout=15)
+ assert a.exitcode == 0, f"worker A failed: {a.exitcode}"
+ assert b.exitcode == 0, f"worker B failed: {b.exitcode}"
+
+ loaded = V2Config.load()
+ # Both writes survive.
+ assert loaded.language == "zh"
+ assert loaded.runtime.log_level == "DEBUG"
+ # B's snapshot was loaded after A's save (inside the lock).
+ assert saw_queue.get(timeout=5) == "zh"
+
+
+def test_mutator_exception_aborts_without_write(isolated_config_home: Path) -> None:
+ def boom(cfg: V2Config) -> None:
+ cfg.language = "zh"
+ raise RuntimeError("mutator failed")
+
+ with pytest.raises(RuntimeError):
+ update_config_fields(boom)
+ assert V2Config.load().language == "en"
+
+
+def test_plain_load_save_pair_loses_interleaved_write(
+ isolated_config_home: Path,
+) -> None:
+ """The race baseline: a load→mutate→save cycle outside the
+ transaction reverts fields committed between its load and its save.
+ Guards against 'just use CONFIG_LOCK' regressions by keeping the
+ failing shape executable."""
+
+ stale = V2Config.load() # snapshot taken early
+
+ # A concurrent transactional writer commits in between.
+ update_config_fields(lambda cfg: setattr(cfg, "language", "zh"))
+
+ stale.save() # writes the early snapshot
+
+ loaded = V2Config.load()
+ # The interleaved write was reverted by the stale full-snapshot
+ # save — exactly the #1458 defect class.
+ assert loaded.language == "en"
+
+
+def test_transaction_reentrant_with_save(isolated_config_home: Path) -> None:
+ """save() itself opens the Memory transaction; the write transaction
+ must re-enter cleanly rather than deadlock on the held file lock."""
+
+ def mutator(cfg: V2Config) -> None:
+ cfg.agents.codex.oauth_relay_marker = {"provider_id": "OpenAI", "base_url": "https://r/v1"}
+
+ update_config_fields(mutator)
+ assert V2Config.load().agents.codex.oauth_relay_marker == {
+ "provider_id": "OpenAI",
+ "base_url": "https://r/v1",
+ }
diff --git a/vibe/api.py b/vibe/api.py
index 4e88e074f..e1b55f421 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -11997,13 +11997,12 @@ def set_opencode_default_provider(payload: dict) -> dict:
return {"ok": False, "message": "provider_id is required"}
provider_id = raw.strip()
- with CONFIG_LOCK:
- try:
- config = load_config()
- except FileNotFoundError:
- config = V2Config()
- config.agents.opencode.default_provider = provider_id
- config.save()
+ from config.v2_config import update_config_fields
+
+ def _apply(cfg: V2Config) -> None:
+ cfg.agents.opencode.default_provider = provider_id
+
+ update_config_fields(_apply)
return {"ok": True, "default_provider": provider_id}
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index 59d1ba9e3..5b96f9130 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -533,20 +533,16 @@ def persist_codex_relay_marker(marker: Optional[Dict[str, str]]) -> bool:
``save_codex_auth`` — can persist a fresh capture BEFORE the
destructive ``apply_codex_auth(oauth)`` cleanup destroys the on-disk
relay evidence (#1450). A later V2Config failure in the owning flow
- then cannot lose the capture. Returns ``True`` when the write
- landed; ``False`` (never raises) so callers can degrade to "recovery
- lost, OAuth proceeds".
+ then cannot lose the capture. Runs through the cross-process
+ ``update_config_fields`` transaction (#1458) so the marker write
+ cannot revert a concurrent Settings save from the other process.
+ Returns ``True`` when the write landed; ``False`` (never raises) so
+ callers can degrade to "recovery lost, OAuth proceeds".
"""
- from config.v2_config import CONFIG_LOCK, V2Config
+ from config.v2_config import update_config_fields
try:
- with CONFIG_LOCK:
- try:
- config = V2Config.load()
- except FileNotFoundError:
- config = V2Config.default()
- config.agents.codex.oauth_relay_marker = marker
- config.save()
+ update_config_fields(lambda config: setattr(config.agents.codex, "oauth_relay_marker", marker))
return True
except Exception: # noqa: BLE001
return False
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 78851a796..1b8763303 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -3600,8 +3600,19 @@ def stop(config: V2Config | None = None) -> dict[str, Any]:
def rotate_session_secret(config: V2Config) -> None:
- config.remote_access.vibe_cloud.session_secret = secrets.token_urlsafe(32)
- config.save()
+ """Rotate the cloud session secret through the cross-process write
+ transaction (#1458) so the rotation cannot revert a concurrent
+ Settings save, and mirror the new secret onto the caller's live
+ config object."""
+ from config.v2_config import update_config_fields
+
+ new_secret = secrets.token_urlsafe(32)
+
+ def _apply(cfg: V2Config) -> None:
+ cfg.remote_access.vibe_cloud.session_secret = new_secret
+
+ update_config_fields(_apply)
+ config.remote_access.vibe_cloud.session_secret = new_secret
def start(config: V2Config | None = None) -> dict[str, Any]: