|
| 1 | +# User Groups Discrepancy Issue |
| 2 | + |
| 3 | +## Summary |
| 4 | + |
| 5 | +We've identified a discrepancy between the database state and API responses when retrieving user groups. When a user requests their groups, they're not receiving all groups where they are members. Specifically, when user ID `1062` requests their groups, they should receive 3 groups (IDs 22, 25, and 28), but only receive 2 groups (IDs 25 and 28). |
| 6 | + |
| 7 | +## Investigation Details |
| 8 | + |
| 9 | +### Debug Logs |
| 10 | + |
| 11 | +The logs show only two groups being returned: |
| 12 | + |
| 13 | +``` |
| 14 | +2025-05-21 21:38:17,604 - src.routers.user_groups - DEBUG - Fetching groups for user 1062... |
| 15 | +2025-05-21 21:38:17,604 - src.database.user_groups - DEBUG - Getting user groups with users for user_id: 1062 |
| 16 | +2025-05-21 21:38:17,604 - src.database.user_groups - DEBUG - Fetching groups where user 1062 is a member... |
| 17 | +2025-05-21 21:38:18,656 - src.database.user_groups - DEBUG - Found 1 groups where user 1062 is a member: [28] |
| 18 | +2025-05-21 21:38:18,656 - src.database.user_groups - DEBUG - Fetching groups where user 1062 is an admin... |
| 19 | +2025-05-21 21:38:19,606 - src.database.user_groups - DEBUG - Found 1 groups where user 1062 is an admin: [25] |
| 20 | +2025-05-21 21:38:19,606 - src.database.user_groups - DEBUG - Added 1 additional groups as admin (not already as member): [25] |
| 21 | +2025-05-21 21:38:19,606 - src.database.user_groups - DEBUG - Total: Found 2 user groups with users for user_id: 1062, Group IDs: [25, 28] |
| 22 | +``` |
| 23 | + |
| 24 | +### Database State |
| 25 | + |
| 26 | +Our database queries confirm that the user should be in 3 groups: |
| 27 | + |
| 28 | +```sql |
| 29 | +SELECT id, name, user_ids, admin_ids |
| 30 | +FROM user_groups |
| 31 | +WHERE 1062 = ANY(user_ids) OR 1062 = ANY(admin_ids) |
| 32 | +ORDER BY id; |
| 33 | +``` |
| 34 | + |
| 35 | +Result: |
| 36 | +``` |
| 37 | + id | name | user_ids | admin_ids |
| 38 | +----+-------------+-----------------+----------- |
| 39 | + 22 | UNDP Studio | {1062,774,1067} | {} |
| 40 | + 25 | GROUP 3 | {1062} | {1062} |
| 41 | + 28 | test4 | {774,1062} | {774} |
| 42 | +``` |
| 43 | + |
| 44 | +### Code Analysis |
| 45 | + |
| 46 | +The code in `user_groups.py` uses the correct SQL syntax to retrieve groups where a user is a member or admin: |
| 47 | + |
| 48 | +1. First query: `SELECT ... FROM user_groups WHERE %s = ANY(user_ids) ORDER BY created_at DESC;` |
| 49 | +2. Second query: `SELECT ... FROM user_groups WHERE %s = ANY(admin_ids) ORDER BY created_at DESC;` |
| 50 | + |
| 51 | +These queries should correctly find all groups, but the first query is only returning group 28, not both 22 and 28 as expected. |
| 52 | + |
| 53 | +## Impact |
| 54 | + |
| 55 | +Users may not see all groups they belong to in the application, which could lead to: |
| 56 | + |
| 57 | +1. Reduced access to signals shared in "missing" groups |
| 58 | +2. Confusion about group membership |
| 59 | +3. Workflow disruptions if users expect to find signals in specific groups |
| 60 | + |
| 61 | +## Possible Causes |
| 62 | + |
| 63 | +1. SQL query execution issues |
| 64 | +2. Application-level filtering not visible in the code |
| 65 | +3. A caching or stale data issue |
| 66 | +4. Transaction isolation level issues |
| 67 | +5. Potential race condition if groups are being modified simultaneously |
| 68 | + |
| 69 | +## Fix Implemented |
| 70 | + |
| 71 | +We've implemented a comprehensive solution with multiple layers of improvements: |
| 72 | + |
| 73 | +### 1. Enhanced Primary Functions |
| 74 | + |
| 75 | +Modified the approach in the affected functions to use a single combined query with explicit array handling: |
| 76 | + |
| 77 | +```python |
| 78 | +# Run a direct SQL query to ensure array type handling is consistent |
| 79 | +query = """ |
| 80 | +SELECT |
| 81 | + id, |
| 82 | + name, |
| 83 | + signal_ids, |
| 84 | + user_ids, |
| 85 | + admin_ids, |
| 86 | + collaborator_map, |
| 87 | + created_at |
| 88 | +FROM |
| 89 | + user_groups |
| 90 | +WHERE |
| 91 | + %s = ANY(user_ids) OR %s = ANY(admin_ids) |
| 92 | +ORDER BY |
| 93 | + created_at DESC; |
| 94 | +""" |
| 95 | + |
| 96 | +await cursor.execute(query, (user_id, user_id)) |
| 97 | +``` |
| 98 | + |
| 99 | +We also added explicit type conversion when checking for user membership: |
| 100 | + |
| 101 | +```python |
| 102 | +# Track membership rigorously by explicitly converting IDs to integers |
| 103 | +is_member = False |
| 104 | +if data['user_ids']: |
| 105 | + is_member = user_id in [int(uid) for uid in data['user_ids']] |
| 106 | + |
| 107 | +is_admin = False |
| 108 | +if data['admin_ids']: |
| 109 | + is_admin = user_id in [int(aid) for aid in data['admin_ids']] |
| 110 | +``` |
| 111 | + |
| 112 | +### 2. Debug Functions |
| 113 | + |
| 114 | +Added a `debug_user_groups` function that runs multiple direct queries to diagnose issues: |
| 115 | + |
| 116 | +```python |
| 117 | +async def debug_user_groups(cursor: AsyncCursor, user_id: int) -> dict: |
| 118 | + # Various direct SQL queries to check database state |
| 119 | + # and array position functions |
| 120 | + # ... |
| 121 | +``` |
| 122 | + |
| 123 | +### 3. Fallback Implementation |
| 124 | + |
| 125 | +Created a completely separate direct SQL implementation in `user_groups_direct.py` as a fallback: |
| 126 | + |
| 127 | +```python |
| 128 | +async def get_user_groups_direct(cursor: AsyncCursor, user_id: int) -> List[UserGroup]: |
| 129 | + """ |
| 130 | + Get all groups that a user is a member of or an admin of using direct SQL. |
| 131 | + """ |
| 132 | + # Simple, direct SQL with minimal processing |
| 133 | + # ... |
| 134 | +``` |
| 135 | + |
| 136 | +### 4. Automatic Fallback in API |
| 137 | + |
| 138 | +Modified the user groups router to automatically detect and handle discrepancies: |
| 139 | + |
| 140 | +```python |
| 141 | +# Check if there's a mismatch between direct query and regular function |
| 142 | +if missing_ids: |
| 143 | + logger.warning(f"MISMATCH! Direct query found groups {direct_group_ids} but function returned only {fetched_ids}") |
| 144 | + logger.warning(f"Missing groups: {missing_ids}") |
| 145 | + |
| 146 | + # Fall back to direct SQL implementation |
| 147 | + logger.warning("Falling back to direct SQL implementation") |
| 148 | + user_groups = await user_groups_direct.get_user_groups_with_users_direct(cursor, user.id) |
| 149 | + logger.info(f"Direct SQL implementation returned {len(user_groups)} groups") |
| 150 | +``` |
| 151 | + |
| 152 | +These changes ensure: |
| 153 | +- More reliable querying of user group memberships |
| 154 | +- Better debug information if issues persist |
| 155 | +- Automatic fallback to a simpler implementation if needed |
| 156 | +- More detailed logging throughout the process |
| 157 | + |
| 158 | +After these changes, users should see all groups where they are members or admins consistently. |
| 159 | + |
| 160 | +## Additional Fix: Signal Entity can_edit Attribute |
| 161 | + |
| 162 | +During testing, we discovered that the Signal entity was missing the `can_edit` attribute that's dynamically added in user group contexts. This caused AttributeError exceptions when trying to access `signal.can_edit`. |
| 163 | + |
| 164 | +### Issue |
| 165 | +```python |
| 166 | +AttributeError: 'Signal' object has no attribute 'can_edit' |
| 167 | +``` |
| 168 | + |
| 169 | +### Solution |
| 170 | +Added the `can_edit` field to the Signal entity definition: |
| 171 | + |
| 172 | +```python |
| 173 | +can_edit: bool = Field( |
| 174 | + default=False, |
| 175 | + description="Whether the current user can edit this signal (set dynamically based on group membership and collaboration).", |
| 176 | +) |
| 177 | +``` |
| 178 | + |
| 179 | +This ensures that: |
| 180 | +- The Signal model accepts the `can_edit` attribute when created |
| 181 | +- The attribute defaults to `False` for signals that don't have edit permissions |
| 182 | +- Both the regular and direct SQL implementations can properly set this attribute |
| 183 | +- Frontend code can safely access `signal.can_edit` without errors |
| 184 | + |
| 185 | +The fix has been applied to both endpoints: |
| 186 | +1. `/user-groups/me` (user groups without signals) |
| 187 | +2. `/user-groups/me/with-signals` (user groups with signals) |
| 188 | + |
| 189 | +Both endpoints now include the same debug checks and automatic fallback to direct SQL if discrepancies are detected. |
0 commit comments