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): preserve mutation cache freshness
Maxecb0f98d8c52
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.pyindex 630e6a28b..76c926a11 100644--- a/storage/resource_access_service.py+++ b/storage/resource_access_service.py@@ -658,6 +658,56 @@ def _resolve_authoritative_show_page_ownership(return dict(ownership)+def _show_page_authorization_ownership(+ connection: Connection | None,+ ownership: Mapping[str, Any] | None = None,+) -> dict[str, Any]:+ """Resolve the pairing fence before the authorization transaction reads state."""++ if ownership is not None:+ return _resolve_authoritative_show_page_ownership(dict(ownership))++ # With no caller-owned connection, finish the small persisted-fence read+ # before resolving the potentially slow authoritative organization lookup.+ if connection is None:+ return _resolve_authoritative_show_page_ownership(+ current_show_page_instance_ownership()+ )++ configured = _configured_show_page_instance()+ if configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE:+ return _configuration_unavailable_ownership()+ if configured is None:+ return {+ "mode": "unmanaged",+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }+ instance_id, instance_kind = configured+ if instance_kind == "personal":+ return {+ "mode": "personal",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }++ # A supplied Connection may contain an uncommitted legacy policy. Resolve+ # the organization fence before its first SELECT so reconciliation can+ # safely write through that same transaction.+ provisional = {+ "mode": "organization_pending",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+ resolved = _resolve_authoritative_show_page_ownership(provisional)+ if resolved.get("mode") == "organization":+ return resolved+ return current_show_page_instance_ownership(connection=connection)++def _show_page_authorization_snapshot(connection: Connection,resource_id: str,@@ -667,12 +717,12 @@ def _show_page_authorization_snapshot("""Load one policy after adopting a legacy null-organization shape when safe."""identifier = _required_identifier(resource_id, code="invalid_resource_id")- policy = _policy_row(connection, "show_page", identifier)current_ownership = dict(ownershipif ownership is not None- else current_show_page_instance_ownership(connection=connection)+ else _show_page_authorization_ownership(connection))+ policy = _policy_row(connection, "show_page", identifier)policy_organization = _clean_optional_string(policy.get("organization_id") if policy else None)@@ -681,20 +731,18 @@ def _show_page_authorization_snapshot(and policy_organization is Noneand current_ownership.get("mode") in {"organization", "organization_pending"}):- resolved_ownership = _resolve_authoritative_show_page_ownership(current_ownership)- if resolved_ownership.get("mode") == "organization":- try:- reconciliation = reconcile_show_page_resource_policy(- connection,- resource_id=identifier,- ownership=resolved_ownership,- owner_user_id=_clean_optional_string(policy.get("owner_user_id")),- owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),- )- except ResourceAccessError:- return _configuration_unavailable_ownership(), policy, []- current_ownership = dict(reconciliation["ownership"])- policy = reconciliation["policy"]+ try:+ reconciliation = reconcile_show_page_resource_policy(+ connection,+ resource_id=identifier,+ ownership=current_ownership,+ owner_user_id=_clean_optional_string(policy.get("owner_user_id")),+ owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),+ )+ except ResourceAccessError:+ return _configuration_unavailable_ownership(), policy, []+ current_ownership = dict(reconciliation["ownership"])+ policy = reconciliation["policy"]groups = _policy_groups(connection, "show_page", identifier) if policy else []return current_ownership, policy, groups@@ -1107,9 +1155,18 @@ def can_use_resource(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")+ show_page_ownership = (+ _show_page_authorization_ownership(connection)+ if kind == "show_page"+ else None+ )with _connection(connection) as conn:if kind == "show_page":- ownership, policy, groups = _show_page_authorization_snapshot(conn, identifier)+ ownership, policy, groups = _show_page_authorization_snapshot(+ conn,+ identifier,+ ownership=show_page_ownership,+ )else:policy = _policy_row(conn, kind, identifier)groups = _policy_groups(conn, kind, identifier) if policy else []@@ -1134,9 +1191,18 @@ def can_manage_resource_acl(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")+ show_page_ownership = (+ _show_page_authorization_ownership(connection)+ if kind == "show_page"+ else None+ )with _connection(connection) as conn:if kind == "show_page":- ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)+ ownership, policy, _groups = _show_page_authorization_snapshot(+ conn,+ identifier,+ ownership=show_page_ownership,+ )else:ownership = Nonepolicy = _policy_row(conn, kind, identifier)@@ -1162,8 +1228,13 @@ def can_manage_show_page_access(context = _as_context(user_context)identifier = _required_identifier(resource_id, code="invalid_resource_id")+ show_page_ownership = _show_page_authorization_ownership(connection)with _connection(connection) as conn:- ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)+ ownership, policy, _groups = _show_page_authorization_snapshot(+ conn,+ identifier,+ ownership=show_page_ownership,+ )if (not context.is_instance_ownerand not _show_page_policy_matches_instance_ownership(@@ -1187,9 +1258,18 @@ def can_control_resource_sharing(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")+ show_page_ownership = (+ _show_page_authorization_ownership(connection)+ if kind == "show_page"+ else None+ )with _connection(connection) as conn:if kind == "show_page":- ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)+ ownership, policy, _groups = _show_page_authorization_snapshot(+ conn,+ identifier,+ ownership=show_page_ownership,+ )else:ownership = Nonepolicy = _policy_row(conn, kind, identifier)@@ -1240,6 +1320,11 @@ def filter_accessible_resources(identifiers = [identifier for _, identifier in candidates if identifier is not None]if not identifiers:return []+ ownership = (+ _show_page_authorization_ownership(connection)+ if kind == "show_page"+ else None+ )with _connection(connection) as conn:policy_rows = conn.execute(select(resource_access_policies)@@ -1251,11 +1336,8 @@ def filter_accessible_resources(identifier: _policy_groups(conn, kind, identifier)for identifier in policies}- ownership = current_show_page_instance_ownership(connection=conn) if kind == "show_page" else Noneif kind == "show_page":- resolved_ownership = _resolve_authoritative_show_page_ownership(ownership)- if resolved_ownership.get("mode") == "organization":- ownership = resolved_ownership+ if ownership and ownership.get("mode") == "organization":for identifier, policy in list(policies.items()):if _clean_optional_string(policy.get("organization_id")) is not None:continuediff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex 90689d2cc..fe96ec863 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -59,11 +59,17 @@ def _cache_projection_process(candidate: dict[str, Any],*,cache_order: int = 0,+ mutation_orders: dict[str, Any] | None = None,) -> None:entered_write.set()if not release_write.wait(10):raise TimeoutError("cache write was not released")- original_write(instance_id, candidate, cache_order=cache_order)+ original_write(+ instance_id,+ candidate,+ cache_order=cache_order,+ mutation_orders=mutation_orders,+ )permissions._write_cache = delayed_write # noqa: SLF001@@ -1004,6 +1010,69 @@ def test_permissions_cache_mutation_rebase_preserves_newer_same_project_policy()assert cached.projection["projects"][0] == newer+def test_permissions_cache_mutation_rebase_preserves_newer_authorized_users_entries() -> None:+ base = _complete_projection()+ newer_entries = [+ {"kind": "email", "value": "[email protected]", "role": "editor"}+ ]+ delayed_entries = [+ {"kind": "email", "value": "[email protected]", "role": "viewer"}+ ]+ permissions._cache_projection( # noqa: SLF001+ "inst-123",+ base,+ request_order=18,+ )++ # The newer authorized-users mutation commits first; its delayed response+ # must remain authoritative for access entries across a process rebase.+ permissions._cache_mutation_result( # noqa: SLF001+ "inst-123",+ 5,+ access_entries=newer_entries,+ request_order=20,+ )+ permissions._cache_mutation_result( # noqa: SLF001+ "inst-123",+ 4,+ access_entries=delayed_entries,+ request_order=19,+ )++ cached = permissions._read_cache("inst-123") # noqa: SLF001+ assert cached is not None+ assert cached.cache_order == 20+ assert cached.projection["instance"]["authorization_revision"] == 5+ assert cached.projection["access"]["entries"] == newer_entries+++def test_permissions_live_read_rechecks_pairing_after_cache_write_failure(monkeypatch) -> None:+ config = _config()+ switched = False++ def failed_write(*_args, **_kwargs):+ nonlocal switched+ if not switched:+ switched = True+ replacement = V2Config.load()+ replacement.remote_access.vibe_cloud.instance_id = "inst-new"+ replacement.save()+ raise OSError("read-only state")++ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, _projection()),+ )+ monkeypatch.setattr(permissions, "_write_cache", failed_write)++ with pytest.raises(+ permissions.PermissionsPairingChangedError,+ match="permissions_pairing_changed",+ ):+ permissions.get_current_permissions(config)++@pytest.mark.parametrize("entity", ["access", "project"])def test_permissions_cache_replays_superseded_mutation_entity_without_lowering_revision(entity: str,diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.pyindex 7105324b0..0ce5e932a 100644--- a/tests/test_resource_access_service.py+++ b/tests/test_resource_access_service.py@@ -6,6 +6,7 @@ from config.v2_config import V2Configfrom storage import resource_access_servicefrom storage.db import create_sqlite_enginefrom storage.migrations import run_migrations+from storage.models import state_metafrom vibe import permissions@@ -310,6 +311,77 @@ def test_show_page_authorizers_adopt_legacy_policy_before_enforcing_organizationengine.dispose()+def test_show_page_legacy_reconciliation_reopens_after_authority_lookup(+ monkeypatch,+ tmp_path,+) -> None:+ """An authority lookup must finish before the legacy policy read snapshot."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ config = V2Config.default()+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.backend_url = "https://backend.example"+ cloud.instance_id = "inst-1"+ cloud.instance_secret = "device-secret"+ cloud.instance_kind = "organization"+ config.save()+ db = tmp_path / "vibe.sqlite"+ run_migrations(db)+ engine = create_sqlite_engine(db)+ owner = _context("owner-1", instance_role="editor")++ try:+ with engine.begin() as connection:+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id="legacy-page",+ organization_id=None,+ owner_user_id="owner-1",+ access_level="private",+ )++ def resolve_ownership() -> dict[str, str]:+ # A concurrent writer commits while the authoritative lookup is+ # in flight. The later reconciliation must use a fresh snapshot.+ with engine.begin() as writer:+ writer.execute(+ state_meta.insert().values(+ key="interleaved-lookup",+ value_json="{}",+ updated_at="now",+ )+ )+ return {+ "mode": "organization",+ "instance_id": "inst-1",+ "organization_id": "org-1",+ "source": "live",+ }++ monkeypatch.setattr(permissions, "resolve_current_instance_ownership", resolve_ownership)++ with engine.begin() as connection:+ assert resource_access_service.can_use_resource(+ owner,+ "show_page",+ "legacy-page",+ connection=connection,+ )++ with engine.connect() as connection:+ policy = resource_access_service.get_resource_policy(+ "show_page",+ "legacy-page",+ connection=connection,+ )+ assert policy is not None+ assert policy["organization_id"] == "org-1"+ finally:+ engine.dispose()++@pytest.mark.parametrize(("previous_level", "previous_groups", "updated_level", "updated_groups", "expected"),[diff --git a/vibe/permissions.py b/vibe/permissions.pyindex d786fc743..eb2d61136 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -77,6 +77,7 @@ class PermissionsProjectionResult:source: strcached_at: int | None = Nonecache_order: int = 0+ mutation_orders: dict[str, Any] | None = None@propertydef offline(self) -> bool:@@ -576,17 +577,52 @@ def _write_cache(projection: dict[str, Any],*,cache_order: int = 0,+ mutation_orders: Mapping[str, Any] | None = None,) -> None:- _atomic_write_json(- _cache_path(),- {- "cache_schema_version": CACHE_SCHEMA_VERSION,- "instance_id": instance_id,- "cached_at": int(time.time()),- "cache_order": cache_order,- "projection": projection,- },- )+ envelope = {+ "cache_schema_version": CACHE_SCHEMA_VERSION,+ "instance_id": instance_id,+ "cached_at": int(time.time()),+ "cache_order": cache_order,+ "projection": projection,+ }+ normalized_orders = _normalize_mutation_orders(mutation_orders, projection)+ if normalized_orders:+ envelope["mutation_orders"] = normalized_orders+ _atomic_write_json(_cache_path(), envelope)+++def _valid_cache_order(value: Any) -> bool:+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0+++def _normalize_mutation_orders(+ value: Any,+ projection: Mapping[str, Any],+) -> dict[str, Any]:+ """Keep optional per-entity mutation freshness metadata well-shaped."""++ if not isinstance(value, Mapping):+ return {}+ normalized: dict[str, Any] = {}+ access_order = value.get("access")+ if _valid_cache_order(access_order):+ normalized["access"] = access_order+ project_orders = value.get("projects")+ if isinstance(project_orders, Mapping):+ project_ids = {+ project.get("project_id")+ for project in projection.get("projects", [])+ if isinstance(project, Mapping)+ }+ normalized_projects = {+ str(project_id): order+ for project_id, order in project_orders.items()+ if project_id in project_ids and _valid_cache_order(order)+ }+ if normalized_projects:+ normalized["projects"] = normalized_projects+ return normalizeddef _read_cache(instance_id: str) -> PermissionsProjectionResult | None:@@ -610,11 +646,16 @@ def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:projection = _validated_projection(envelope.get("projection"), instance_id)except PermissionsInvalidResponseError:return None+ mutation_orders = _normalize_mutation_orders(+ envelope.get("mutation_orders"),+ projection,+ )return PermissionsProjectionResult(projection=projection,source="cache",cached_at=cached_at,cache_order=cache_order,+ mutation_orders=mutation_orders,)@@ -754,10 +795,23 @@ def _merge_equal_revision_projection(def _merge_mutation_rebase_projection(cached: dict[str, Any],candidate: dict[str, Any],+ *,+ mutation_target: tuple[str, str | None] | None,+ cached_mutation_orders: Mapping[str, Any],+ request_order: int,) -> dict[str, Any]:- """Apply mutation policy fields while retaining newer cached sync state."""+ """Apply a delayed mutation without regressing newer entity state."""merged = _prefer_mapping(candidate, cached)+ if mutation_target is not None and mutation_target[0] == "access":+ cached_access_order = cached_mutation_orders.get("access")+ if _valid_cache_order(cached_access_order) and cached_access_order > request_order:+ # Access entries have no backend entity revision. Their mutation+ # order is the only durable ordering signal across processes.+ merged["access"] = _prefer_mapping(+ cached["access"],+ candidate["access"],+ )cached_projects = {project["project_id"]: project for project in cached["projects"]}@@ -786,6 +840,8 @@ def _cache_read_merge_write(*,request_order: int,mutation_rebase: bool = False,+ mutation_target: tuple[str, str | None] | None = None,+ complete_projection: bool = False,pairing_guard: Callable[[], None] | None = None,) -> None:"""Read, merge, and atomically replace one instance cache under one lock."""@@ -803,6 +859,10 @@ def _cache_read_merge_write(returnvalidated = _validated_projection(candidate, instance_id)cache_order = request_order+ cached_mutation_orders = (+ cached.mutation_orders if cached is not None else {}+ ) or {}+ candidate_wins_complete_projection = cached is Noneif cached is not None:cached_revision = cached.projection["instance"]["authorization_revision"@@ -813,6 +873,13 @@ def _cache_read_merge_write(if cached_revision > candidate_revision:returncache_order = max(cached.cache_order, request_order)+ candidate_wins_complete_projection = (+ candidate_revision > cached_revision+ or (+ candidate_revision == cached_revision+ and request_order >= cached.cache_order+ )+ )if cached_revision == candidate_revision and not mutation_rebase:validated = _merge_equal_revision_projection(cached.projection,@@ -832,11 +899,36 @@ def _cache_read_merge_write(validated = _merge_mutation_rebase_projection(cached.projection,validated,+ mutation_target=mutation_target,+ cached_mutation_orders=cached_mutation_orders,+ request_order=request_order,)validated = _validated_projection(validated, instance_id)+ mutation_orders = dict(cached_mutation_orders)+ if complete_projection and candidate_wins_complete_projection:+ # A newer complete read is authoritative for every entity;+ # older mutation markers must not affect later rebases.+ mutation_orders = {}+ elif mutation_target is not None:+ target_kind, target_id = mutation_target+ if target_kind == "access":+ current_order = mutation_orders.get("access")+ if not _valid_cache_order(current_order) or request_order > current_order:+ mutation_orders["access"] = request_order+ elif target_kind == "project" and target_id is not None:+ project_orders = dict(mutation_orders.get("projects") or {})+ current_order = project_orders.get(target_id)+ if not _valid_cache_order(current_order) or request_order > current_order:+ project_orders[target_id] = request_order+ mutation_orders["projects"] = project_ordersif pairing_guard is not None:pairing_guard()- _write_cache(instance_id, validated, cache_order=cache_order)+ _write_cache(+ instance_id,+ validated,+ cache_order=cache_order,+ mutation_orders=mutation_orders,+ )except (OSError, TimeoutError):logger.warning("Unable to cache the current Permissions projection", exc_info=True)@@ -853,6 +945,7 @@ def _cache_projection(instance_id,lambda _cached: projection,request_order=order,+ complete_projection=True,pairing_guard=pairing_guard,)@@ -916,6 +1009,13 @@ def _cache_mutation_result(merge,request_order=order,mutation_rebase=True,+ mutation_target=(+ ("access", None)+ if access_entries is not None+ else ("project", str(project.get("project_id")))+ if project is not None+ else None+ ),pairing_guard=pairing_guard,)@@ -1008,6 +1108,9 @@ def get_current_permissions(config: V2Config | None = None) -> PermissionsProjecrequest_order=request_order,pairing_guard=pairing_guard,)+ # Cache persistence is best effort; it may fail before its locked+ # boundary guard runs. Recheck before publishing the live projection.+ pairing_guard()return PermissionsProjectionResult(projection=projection,source="live",@@ -1058,6 +1161,7 @@ def replace_authorized_users(request_order=request_order,pairing_guard=pairing_guard,)+ pairing_guard()return {**result, "instance_id": instance_id}@@ -1096,6 +1200,7 @@ def update_project_access(request_order=request_order,pairing_guard=pairing_guard,)+ pairing_guard()return {**result, "instance_id": instance_id}