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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(permissions): close fallback and config lock races
Max84d78b05e968
diff --git a/config/v2_config.py b/config/v2_config.pyindex 8eb870143..70533c00f 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -34,6 +34,7 @@ logger = logging.getLogger(__name__)CONFIG_LOCK = threading.RLock()_memory_config_tx_state = threading.local()+_config_file_lock_state = threading.local()def _acquire_memory_config_file_lock(descriptor: int) -> None:@@ -1495,20 +1496,52 @@ def _config_file_lock(path: Path):return MigrationFileLock(path.with_name(f".{path.name}.lock"))+@contextmanager+def _config_file_transaction_lock(path: Path) -> Iterator[None]:+ """Hold one config migration lock, re-entering it within this thread."""++ key = os.path.normcase(os.path.abspath(os.fspath(path)))+ locks = getattr(_config_file_lock_state, "locks", None)+ if locks is None:+ locks = {}+ _config_file_lock_state.locks = locks+ active = locks.get(key)+ if active is not None:+ lock, depth = active+ locks[key] = (lock, depth + 1)+ try:+ yield+ finally:+ locks[key] = (lock, depth)+ return++ lock = _config_file_lock(path)+ with lock:+ locks[key] = (lock, 1)+ try:+ yield+ finally:+ del locks[key]++@contextmanagerdef config_file_lock(config_path: Optional[Path] = None) -> Iterator[None]:"""Serialize work that must observe one exact persisted config snapshot.This is the same cross-process transaction used by ``V2Config.save`` and- ``config_write_transaction``. Keeping one lock path for ordinary config- writes and guarded state transitions prevents a pairing update from racing- a reader that is about to persist instance-owned state.+ ``config_write_transaction``. It also takes the migration lock used by+ ``V2Config.load`` while persisting migrations, so ordinary saves cannot+ replace a file between migration verification and replacement. Keeping one+ lock path for ordinary config writes and guarded state transitions prevents+ a pairing update from racing a reader that is about to persist+ instance-owned state."""path = config_path or paths.get_config_path()path.parent.mkdir(parents=True, exist_ok=True)with _memory_config_transaction(path):- yield+ with _config_file_transaction_lock(path):+ yielddef _write_config_payload(path: Path, payload: dict) -> None:@@ -1564,7 +1597,7 @@ def _persist_migrated_config_payload(try:with CONFIG_LOCK:- with _config_file_lock(path):+ with _config_file_transaction_lock(path):try:current_raw = path.read_text(encoding="utf-8")except (OSError, UnicodeDecodeError) as exc:diff --git a/tests/test_config_write_transaction.py b/tests/test_config_write_transaction.pyindex 709f8e038..3f50c28a8 100644--- a/tests/test_config_write_transaction.py+++ b/tests/test_config_write_transaction.py@@ -74,6 +74,31 @@ def _txn_worker_b(home: str, attempted: threading.Event, done: threading.Event,done.set()+def _migration_lock_worker(home: str, entered: threading.Event, release: threading.Event) -> None:+ import os as _os++ _os.environ["AVIBE_HOME"] = home+ from config import paths as _paths+ from config.v2_config import _config_file_lock++ with _config_file_lock(_paths.get_config_path()):+ entered.set()+ assert release.wait(timeout=15), "migration lock worker never released"+++def _ordinary_save_worker(home: str, attempted: threading.Event, done: threading.Event) -> None:+ import os as _os++ _os.environ["AVIBE_HOME"] = home+ from config.v2_config import V2Config++ attempted.set()+ config = V2Config.load()+ config.language = "zh"+ config.save()+ done.set()++def test_transaction_blocks_second_process_until_first_releases(isolated_config_home: Path,) -> None:@@ -121,6 +146,42 @@ def test_transaction_blocks_second_process_until_first_releases(assert saw_queue.get(timeout=5) == "zh"+def test_ordinary_save_waits_for_migration_file_lock(+ isolated_config_home: Path,+) -> None:+ """Every ordinary save must share the lock used by migration persistence."""++ import multiprocessing as mp++ ctx = mp.get_context("spawn")+ entered = ctx.Event()+ release = ctx.Event()+ attempted = ctx.Event()+ done = ctx.Event()+ home = str(isolated_config_home.parent.parent)++ migration = ctx.Process(+ target=_migration_lock_worker,+ args=(home, entered, release),+ )+ saver = ctx.Process(+ target=_ordinary_save_worker,+ args=(home, attempted, done),+ )+ migration.start()+ assert entered.wait(timeout=15), "migration worker never acquired its lock"+ saver.start()+ assert attempted.wait(timeout=15), "save worker never reached save"+ assert not done.wait(timeout=1.0), "ordinary save bypassed the migration file lock"++ release.set()+ migration.join(timeout=15)+ saver.join(timeout=15)+ assert migration.exitcode == 0, f"migration worker failed: {migration.exitcode}"+ assert saver.exitcode == 0, f"save worker failed: {saver.exitcode}"+ assert V2Config.load().language == "zh"++def test_mutator_exception_aborts_without_write(isolated_config_home: Path) -> None:def boom(cfg: V2Config) -> None:cfg.language = "zh"diff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex 3573d8063..a84eb3bdc 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -1203,6 +1203,41 @@ def test_permissions_rejects_cached_fallback_after_inflight_pairing_change(permissions.get_current_permissions(config)+def test_permissions_rechecks_pairing_after_loading_cached_fallback(+ monkeypatch,+) -> None:+ config = _config()+ cached_projection = _complete_projection()+ permissions._write_cache("inst-123", cached_projection) # noqa: SLF001+ original_read = permissions._read_cache # noqa: SLF001+ read_count = 0++ def read_cache(instance_id: str):+ nonlocal read_count+ read_count += 1+ cached = original_read(instance_id)+ if read_count == 2:+ replacement = V2Config.load()+ replacement.remote_access.vibe_cloud.instance_id = "inst-new"+ replacement.save()+ return cached++ monkeypatch.setattr(permissions, "_read_cache", read_cache)+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(requests.ConnectionError()),+ )++ with pytest.raises(+ permissions.PermissionsPairingChangedError,+ match="permissions_pairing_changed",+ ):+ permissions.get_current_permissions(config)++ assert read_count >= 2++@pytest.mark.parametrize("operation", ["get", "authorized_users", "project_access"])def test_permissions_cache_write_rechecks_pairing_for_every_projection_writer(monkeypatch,diff --git a/vibe/permissions.py b/vibe/permissions.pyindex 460fc230d..dfececff3 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -615,6 +615,18 @@ def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:)+def _read_pairing_bound_cache(+ instance_id: str,+ pairing_guard: Callable[[], None],+) -> PermissionsProjectionResult | None:+ """Read a fallback projection only while the captured pairing remains current."""++ pairing_guard()+ cached = _read_cache(instance_id)+ pairing_guard()+ return cached++def _read_cache_order() -> int:try:value = json.loads(_cache_order_path().read_text(encoding="utf-8"))@@ -982,15 +994,13 @@ def get_current_permissions(config: V2Config | None = None) -> PermissionsProjeccache_order=request_order,)except PermissionsUnavailableError:- pairing_guard()- cached = _read_cache(instance_id)+ cached = _read_pairing_bound_cache(instance_id, pairing_guard)if cached is not None:return cachedraiseexcept PermissionsBackendError as exc:if _is_backend_unavailable_status(exc.status):- pairing_guard()- cached = _read_cache(instance_id)+ cached = _read_pairing_bound_cache(instance_id, pairing_guard)if cached is not None:return cachedraise