Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: route unclaimed automation events to the default org on single-org installs (#14745)

Alona282cc8c8e20d
diff --git a/enterprise/server/services/automation_event_service.py b/enterprise/server/services/automation_event_service.py
index 9cd05190e3..c9c485c4c3 100644
--- a/enterprise/server/services/automation_event_service.py
+++ b/enterprise/server/services/automation_event_service.py
@@ -34,6 +34,11 @@ from server.auth.constants import (
AUTOMATION_WEBHOOK_SECRET,
)
from server.auth.token_manager import TokenManager
+from storage.default_org_service import (
+ get_default_org_config,
+ is_personal_workspace_org,
+)
+from storage.org_store import OrgStore
from storage.redis import get_redis_client_async
from openhands.app_server.integrations.provider import ProviderType
@@ -42,10 +47,13 @@ from openhands.app_server.utils.logger import openhands_logger as logger
# Cache TTL constants
ORG_CLAIM_CACHE_TTL_SECONDS = 3600 # 1 hour for org claims (rarely change)
USER_ID_CACHE_TTL_SECONDS = 86400 # 24 hours for user ID mappings (never change)
+# Short TTL so creating a second team org switches the fallback off promptly.
+DEFAULT_ORG_FALLBACK_CACHE_TTL_SECONDS = 300
# Cache key prefixes (provider is appended dynamically)
ORG_CLAIM_CACHE_PREFIX = 'automation:org_claim'
USER_ID_CACHE_PREFIX = 'automation:idp_to_kc_user'
+DEFAULT_ORG_FALLBACK_CACHE_KEY = 'automation:default_org_fallback'
@dataclass
@@ -216,6 +224,12 @@ class AutomationEventService:
f'{git_org_name} to personal org {org_id} ({provider.value})'
)
+ # Fallback for single-org installs with a bootstrapped default org:
+ # route unclaimed repos there instead of dropping the event. Claims
+ # always take precedence above.
+ if not org_id:
+ org_id = await self._resolve_default_org_fallback(provider, git_org_name)
+
if not org_id:
logger.warning(
f'[AutomationEventService] {provider.value} org {git_org_name} '
@@ -225,6 +239,47 @@ class AutomationEventService:
return OrgContext(org_id=org_id, git_org=git_org_name)
+ async def _resolve_default_org_fallback(
+ self, provider: ProviderType, git_org_name: str
+ ) -> UUID | None:
+ """Resolve unclaimed events to the bootstrapped default org.
+
+ Applies only when a default org is configured (OPENHANDS_DEFAULT_ORG_*)
+ and exactly one team org exists in the install β€” the default org
+ itself (with zero team orgs the default org has not been created yet,
+ so nothing resolves). The moment a second team org exists the
+ fallback switches off (within the cache TTL) and routing reverts to
+ explicit claims, so events can never cross org boundaries in
+ multi-org installs.
+ """
+ config = get_default_org_config()
+ if not (config.enabled and config.org_name):
+ return None
+
+ cached = await self._get_cached_value(DEFAULT_ORG_FALLBACK_CACHE_KEY)
+ if cached is not None:
+ return None if cached == 'none' else UUID(cached)
+
+ org_id: UUID | None = None
+ org = await OrgStore.get_org_by_name(config.org_name)
+ is_personal = org is not None and is_personal_workspace_org(org)
+ if org and not is_personal and await OrgStore.count_team_orgs() == 1:
+ org_id = org.id
+
+ await self._set_cached_value(
+ DEFAULT_ORG_FALLBACK_CACHE_KEY,
+ str(org_id) if org_id else 'none',
+ DEFAULT_ORG_FALLBACK_CACHE_TTL_SECONDS,
+ )
+
+ if org_id:
+ logger.info(
+ f'[AutomationEventService] Routing unclaimed {provider.value} '
+ f'org {git_org_name} to default org {org_id} '
+ f'(single-org install fallback)'
+ )
+ return org_id
+
def _extract_owner_info(
self, provider: ProviderType, payload: dict[str, Any]
) -> tuple[str | None, str | None, int | None]:
diff --git a/enterprise/storage/default_org_service.py b/enterprise/storage/default_org_service.py
index 12949769f0..e1da07468f 100644
--- a/enterprise/storage/default_org_service.py
+++ b/enterprise/storage/default_org_service.py
@@ -83,6 +83,11 @@ def get_default_org_config() -> DefaultOrgConfig:
)
+def is_personal_workspace_org(org: Org) -> bool:
+ """A personal workspace org is auto-created and named after its user."""
+ return org.name == f'user_{org.id}_org'
+
+
class DefaultOrgBootstrapService:
"""Apply additive default organization membership rules on user login."""
@@ -213,7 +218,7 @@ class DefaultOrgBootstrapService:
@staticmethod
def _is_personal_workspace_org(org: Org) -> bool:
- return org.name == f'user_{org.id}_org'
+ return is_personal_workspace_org(org)
@staticmethod
async def _find_existing_owner_user(owner_emails: frozenset[str]) -> User | None:
diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.py
index 775a38ac28..0b783a1bd4 100644
--- a/enterprise/storage/org_store.py
+++ b/enterprise/storage/org_store.py
@@ -16,7 +16,7 @@ from server.routes.org_models import (
OrgUpdate,
OrphanedUserError,
)
-from sqlalchemy import delete, select, text
+from sqlalchemy import delete, func, select, text
from sqlalchemy.orm import joinedload
from storage.database import a_session_maker
from storage.lite_llm_manager import LiteLlmManager, get_openhands_cloud_key_alias
@@ -171,6 +171,21 @@ class OrgStore:
org = result.scalars().first()
return await OrgStore._validate_org_version(org)
+ @staticmethod
+ async def count_team_orgs() -> int:
+ """Count orgs that are not personal workspaces.
+
+ A personal workspace shares its id with its user, so team orgs are
+ the orgs whose id has no matching user.
+ """
+ async with a_session_maker() as session:
+ result = await session.execute(
+ select(func.count())
+ .select_from(Org)
+ .where(~select(User.id).where(User.id == Org.id).exists())
+ )
+ return int(result.scalar() or 0)
+
@staticmethod
async def _validate_org_version(org: Org | None) -> Org | None:
"""Check if we need to update org version."""
diff --git a/enterprise/tests/unit/server/services/test_automation_event_service.py b/enterprise/tests/unit/server/services/test_automation_event_service.py
index 5235468fe6..9467e4c37a 100644
--- a/enterprise/tests/unit/server/services/test_automation_event_service.py
+++ b/enterprise/tests/unit/server/services/test_automation_event_service.py
@@ -968,3 +968,170 @@ class TestCacheHelpers:
service = create_service(mock_token_manager)
# Should not raise
await service._set_cached_value('test-key', 'test-value', 3600)
+
+
+class TestResolveDefaultOrgFallback:
+ """Tests for the single-org default-org fallback in org resolution."""
+
+ @staticmethod
+ def _team_org(name='AcmeOrg'):
+ org = MagicMock()
+ org.id = uuid.UUID('87654321-4321-8765-4321-876543218765')
+ org.name = name
+ return org
+
+ @pytest.mark.asyncio
+ async def test_fallback_resolves_single_team_org(
+ self, mock_token_manager, monkeypatch
+ ):
+ """
+ GIVEN: A configured default org that is the only team org, no claim
+ WHEN: _resolve_default_org_fallback is called
+ THEN: The default org id is returned and cached
+ """
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_ENABLED', 'true')
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_NAME', 'AcmeOrg')
+ org = self._team_org()
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with (
+ patch(
+ 'server.services.automation_event_service.OrgStore'
+ ) as mock_org_store,
+ patch(REDIS_PATCH, return_value=mock_redis),
+ ):
+ mock_org_store.get_org_by_name = AsyncMock(return_value=org)
+ mock_org_store.count_team_orgs = AsyncMock(return_value=1)
+ service = create_service(mock_token_manager)
+ result = await service._resolve_default_org_fallback(
+ ProviderType.BITBUCKET_DATA_CENTER, 'proj'
+ )
+
+ assert result == org.id
+ mock_redis.setex.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_fallback_disabled_without_default_org_config(
+ self, mock_token_manager, monkeypatch
+ ):
+ """
+ GIVEN: No default org configured
+ WHEN: _resolve_default_org_fallback is called
+ THEN: None is returned without touching the DB
+ """
+ monkeypatch.delenv('OPENHANDS_DEFAULT_ORG_ENABLED', raising=False)
+ mock_redis = AsyncMock()
+
+ with (
+ patch(
+ 'server.services.automation_event_service.OrgStore'
+ ) as mock_org_store,
+ patch(REDIS_PATCH, return_value=mock_redis),
+ ):
+ mock_org_store.get_org_by_name = AsyncMock()
+ service = create_service(mock_token_manager)
+ result = await service._resolve_default_org_fallback(
+ ProviderType.BITBUCKET_DATA_CENTER, 'proj'
+ )
+
+ assert result is None
+ mock_org_store.get_org_by_name.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_fallback_off_with_multiple_team_orgs(
+ self, mock_token_manager, monkeypatch
+ ):
+ """
+ GIVEN: A default org configured but a second team org exists
+ WHEN: _resolve_default_org_fallback is called
+ THEN: None is returned (multi-org installs require explicit claims)
+ """
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_ENABLED', 'true')
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_NAME', 'AcmeOrg')
+ org = self._team_org()
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with (
+ patch(
+ 'server.services.automation_event_service.OrgStore'
+ ) as mock_org_store,
+ patch(REDIS_PATCH, return_value=mock_redis),
+ ):
+ mock_org_store.get_org_by_name = AsyncMock(return_value=org)
+ mock_org_store.count_team_orgs = AsyncMock(return_value=2)
+ service = create_service(mock_token_manager)
+ result = await service._resolve_default_org_fallback(
+ ProviderType.BITBUCKET_DATA_CENTER, 'proj'
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_fallback_cache_hit_skips_db(self, mock_token_manager, monkeypatch):
+ """
+ GIVEN: A cached fallback result
+ WHEN: _resolve_default_org_fallback is called
+ THEN: The cached org id is returned without DB lookups
+ """
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_ENABLED', 'true')
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_NAME', 'AcmeOrg')
+ cached_id = '87654321-4321-8765-4321-876543218765'
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=cached_id.encode())
+
+ with (
+ patch(
+ 'server.services.automation_event_service.OrgStore'
+ ) as mock_org_store,
+ patch(REDIS_PATCH, return_value=mock_redis),
+ ):
+ mock_org_store.get_org_by_name = AsyncMock()
+ service = create_service(mock_token_manager)
+ result = await service._resolve_default_org_fallback(
+ ProviderType.BITBUCKET_DATA_CENTER, 'proj'
+ )
+
+ assert result == uuid.UUID(cached_id)
+ mock_org_store.get_org_by_name.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_unclaimed_bitbucket_dc_event_routes_to_default_org(
+ self, mock_token_manager, bitbucket_dc_pr_payload, monkeypatch
+ ):
+ """
+ GIVEN: An unclaimed Bitbucket DC project on a single-org install
+ WHEN: _resolve_org_context is called
+ THEN: The event resolves to the default org instead of being dropped
+ """
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_ENABLED', 'true')
+ monkeypatch.setenv('OPENHANDS_DEFAULT_ORG_NAME', 'AcmeOrg')
+ org = self._team_org()
+ mock_redis = AsyncMock()
+ mock_redis.get = AsyncMock(return_value=None)
+ mock_redis.setex = AsyncMock()
+
+ with (
+ patch(
+ 'server.services.automation_event_service.resolve_org_for_repo',
+ new_callable=AsyncMock,
+ return_value=None, # No claim
+ ),
+ patch(
+ 'server.services.automation_event_service.OrgStore'
+ ) as mock_org_store,
+ patch(REDIS_PATCH, return_value=mock_redis),
+ ):
+ mock_org_store.get_org_by_name = AsyncMock(return_value=org)
+ mock_org_store.count_team_orgs = AsyncMock(return_value=1)
+ service = create_service(mock_token_manager)
+ context = await service._resolve_org_context(
+ ProviderType.BITBUCKET_DATA_CENTER, bitbucket_dc_pr_payload
+ )
+
+ assert context is not None
+ assert context.org_id == org.id
+ assert context.git_org == 'PROJ'
diff --git a/enterprise/tests/unit/test_org_store.py b/enterprise/tests/unit/test_org_store.py
index f531c8dbef..2627c1d218 100644
--- a/enterprise/tests/unit/test_org_store.py
+++ b/enterprise/tests/unit/test_org_store.py
@@ -1514,3 +1514,20 @@ async def test_update_org_defaults_async_org_not_found():
# Assert
assert result is None
+
+
+async def test_count_team_orgs_excludes_personal_workspaces(async_session_maker):
+ user_id = uuid.uuid4()
+ async with async_session_maker() as session:
+ # Personal workspace: org id matches the user id
+ personal_org = Org(id=user_id, name=f'user_{user_id}_org')
+ session.add(personal_org)
+ await session.commit()
+ session.add(User(id=user_id, current_org_id=user_id))
+ team_org = Org(name='team-org')
+ session.add(team_org)
+ await session.commit()
+
+ with patch('storage.org_store.a_session_maker', async_session_maker):
+ assert await OrgStore.count_team_orgs() == 1
diff --git a/enterprise/uv.lock b/enterprise/uv.lock
new file mode 100644
index 0000000000..7518fc90bf
--- /dev/null
+++ b/enterprise/uv.lock
@@ -0,0 +1,3 @@
+version = 1
+revision = 3
+requires-python = ">=3.12"