Repository navigation
[Fix]: folder sync and watcher lifecycle (#1625) (#1629) #1658
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
8af41d1
db08d25
936a8f4
ffa19a4
fc978ce
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| import uuid | ||
| import os | ||
| from typing import List, Tuple | ||
| from typing import Dict, List, Optional, Tuple | ||
|
|
||
| from fastapi import HTTPException, status | ||
| from app.database.folders import ( | ||
|
|
@@ -23,7 +23,9 @@ def folder_util_add_folder_tree( | |
| Returns the root folder's UUID and the folder map (containing folder_id and parent_id). | ||
| """ | ||
| folders_data = [] | ||
| folder_map = {} # Maps path to (folder_id, parent_id) | ||
| folder_map: Dict[str, Tuple[str, Optional[str]]] = ( | ||
| {} | ||
| ) # Maps path to (folder_id, parent_id) | ||
|
|
||
| for dirpath, dirnames, _ in os.walk(root_path, topdown=True): | ||
| dirpath = os.path.abspath(dirpath) | ||
|
|
@@ -83,6 +85,15 @@ def folder_util_get_filesystem_direct_child_folders(folder_path: str) -> List[st | |
| if os.path.isdir(item_path): | ||
| filesystem_folders.append(os.path.abspath(item_path)) | ||
| return filesystem_folders | ||
| except (FileNotFoundError, NotADirectoryError): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Report non-directory paths accurately. If
|
||
| raise HTTPException( | ||
| status_code=status.HTTP_404_NOT_FOUND, | ||
| detail=ErrorResponse( | ||
| success=False, | ||
| error="Folder not found", | ||
| message=f"Folder '{folder_path}' does not exist on filesystem", | ||
| ).model_dump(), | ||
| ) | ||
| except PermissionError: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -448,7 +448,7 @@ def test_enable_ai_tagging_single_folder(self, mock_enable_batch, client): | |
|
|
||
| def test_enable_ai_tagging_empty_list(self, client): | ||
| """Test enabling AI tagging with empty folder_ids list.""" | ||
| request_data = {"folder_ids": []} | ||
| request_data: dict[str, list[str]] = {"folder_ids": []} | ||
|
|
||
| response = client.post("/folders/enable-ai-tagging", json=request_data) | ||
|
|
||
|
|
@@ -460,7 +460,7 @@ def test_enable_ai_tagging_empty_list(self, client): | |
|
|
||
| def test_enable_ai_tagging_missing_field(self, client): | ||
| """Test enabling AI tagging without folder_ids field.""" | ||
| request_data = {} | ||
| request_data: dict[str, list[str]] = {} | ||
|
|
||
| response = client.post("/folders/enable-ai-tagging", json=request_data) | ||
|
|
||
|
|
@@ -545,7 +545,7 @@ def test_disable_ai_tagging_single_folder(self, mock_disable_batch, client): | |
|
|
||
| def test_disable_ai_tagging_empty_list(self, client): | ||
| """Test disabling AI tagging with empty folder_ids list.""" | ||
| request_data = {"folder_ids": []} | ||
| request_data: dict[str, list[str]] = {"folder_ids": []} | ||
|
|
||
| response = client.post("/folders/disable-ai-tagging", json=request_data) | ||
|
|
||
|
|
@@ -557,7 +557,7 @@ def test_disable_ai_tagging_empty_list(self, client): | |
|
|
||
| def test_disable_ai_tagging_missing_field(self, client): | ||
| """Test disabling AI tagging without folder_ids field.""" | ||
| request_data = {} | ||
| request_data: dict[str, list[str]] = {} | ||
|
|
||
| response = client.post("/folders/disable-ai-tagging", json=request_data) | ||
|
|
||
|
|
@@ -598,8 +598,14 @@ def test_disable_ai_tagging_no_background_processing( | |
| # DELETE /folders/delete-folders - Delete Folders Tests | ||
| # ============================================================================ | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_success(self, mock_delete_batch, client): | ||
| def test_delete_folders_success( | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Test successfully deleting multiple folders.""" | ||
| mock_delete_batch.return_value = 3 | ||
|
|
||
|
|
@@ -618,11 +624,17 @@ def test_delete_folders_success(self, mock_delete_batch, client): | |
| assert data["data"]["folder_ids"] == ["folder-1", "folder-2", "folder-3"] | ||
|
|
||
| mock_delete_batch.assert_called_once_with(["folder-1", "folder-2", "folder-3"]) | ||
| mock_restart_watcher.assert_called_once() | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.utils.memory_curator.memory_curator_prune_empty") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_background_processing_called( | ||
| self, mock_delete_batch: MagicMock, mock_prune: MagicMock, client: TestClient | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_prune: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Pruning and re-curation are both triggered after deleting folders.""" | ||
| mock_delete_batch.return_value = 3 | ||
|
|
@@ -645,10 +657,15 @@ def test_delete_folders_background_processing_called( | |
| _curate_memories, "folder_delete" | ||
| ) | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.utils.memory_curator.memory_curator_prune_empty") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_survives_curation_submission_failure( | ||
| self, mock_delete_batch: MagicMock, mock_prune: MagicMock, client: TestClient | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_prune: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """ | ||
| A broken/shutdown executor must not turn an already-successful | ||
|
|
@@ -675,10 +692,15 @@ def test_delete_folders_survives_curation_submission_failure( | |
| mock_prune.assert_called_once_with() | ||
| client.app.state.executor.submit.assert_called_once() | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.utils.memory_curator.memory_curator_prune_empty") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_survives_pruning_failure( | ||
| self, mock_delete_batch: MagicMock, mock_prune: MagicMock, client: TestClient | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_prune: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Mirror of the submit-failure test -- prune failing doesn't block it either.""" | ||
| mock_delete_batch.return_value = 3 | ||
|
|
@@ -696,8 +718,14 @@ def test_delete_folders_survives_pruning_failure( | |
| _curate_memories, "folder_delete" | ||
| ) | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_single_folder(self, mock_delete_batch, client): | ||
| def test_delete_folders_single_folder( | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Test deleting a single folder.""" | ||
| mock_delete_batch.return_value = 1 | ||
|
|
||
|
|
@@ -712,6 +740,31 @@ def test_delete_folders_single_folder(self, mock_delete_batch, client): | |
| data = response.json() | ||
| assert data["success"] is True | ||
| assert data["data"]["deleted_count"] == 1 | ||
| mock_restart_watcher.assert_called_once() | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_none_deleted( | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Test deleting folders when no folders were found to delete.""" | ||
| mock_delete_batch.return_value = 0 | ||
|
|
||
| response = client.request( | ||
| "DELETE", | ||
| "/folders/delete-folders", | ||
| content='{"folder_ids": ["non-existent-folder"]}', | ||
| headers={"Content-Type": "application/json"}, | ||
| ) | ||
|
|
||
| assert response.status_code == 200 | ||
| data = response.json() | ||
| assert data["success"] is True | ||
| assert data["data"]["deleted_count"] == 0 | ||
| mock_restart_watcher.assert_not_called() | ||
|
|
||
| def test_delete_folders_empty_list(self, client): | ||
| """Test deleting folders with empty folder_ids list.""" | ||
|
|
@@ -728,8 +781,14 @@ def test_delete_folders_empty_list(self, client): | |
| assert data["detail"]["error"] == "Validation Error" | ||
| assert "No folder IDs provided" in data["detail"]["message"] | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| def test_delete_folders_database_error(self, mock_delete_batch, client): | ||
| def test_delete_folders_database_error( | ||
| self, | ||
| mock_delete_batch: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Test handling database errors during folder deletion.""" | ||
| mock_delete_batch.side_effect = Exception("Database connection failed") | ||
|
|
||
|
|
@@ -744,6 +803,7 @@ def test_delete_folders_database_error(self, mock_delete_batch, client): | |
| data = response.json() | ||
| assert data["detail"]["success"] is False | ||
| assert data["detail"]["error"] == "Internal server error" | ||
| mock_restart_watcher.assert_not_called() | ||
|
|
||
| # ============================================================================ | ||
| # GET /folders/all-folders - Get All Folders Tests | ||
|
|
@@ -854,6 +914,87 @@ def test_disable_ai_tagging_no_folders_updated(self, mock_disable_batch, client) | |
| assert data["success"] is True | ||
| assert data["data"]["updated_count"] == 0 | ||
|
|
||
| # ============================================================================ | ||
| # POST /folders/sync-folder - Sync Folder Tests | ||
| # ============================================================================ | ||
|
|
||
| def test_sync_folder_missing_filesystem_folder_returns_404( | ||
| self, client: TestClient | ||
| ) -> None: | ||
| """Test syncing a folder that does not exist on the filesystem returns 404.""" | ||
| request_data = { | ||
| "folder_id": "dummy-folder-id", | ||
| "folder_path": "/non/existent/path/for/picto_py_test_123", | ||
| } | ||
|
|
||
| response = client.post("/folders/sync-folder", json=request_data) | ||
|
|
||
| assert response.status_code == 404 | ||
| data = response.json() | ||
| assert data["detail"]["success"] is False | ||
| assert data["detail"]["error"] == "Folder not found" | ||
| assert "does not exist on filesystem" in data["detail"]["message"] | ||
|
|
||
| @patch("app.utils.folders.os.listdir") | ||
| def test_sync_folder_permission_denied_returns_401( | ||
| self, mock_listdir: MagicMock, client: TestClient | ||
| ) -> None: | ||
| """Test syncing a folder with PermissionError returns 401.""" | ||
| mock_listdir.side_effect = PermissionError("Permission denied") | ||
|
|
||
| request_data = { | ||
| "folder_id": "dummy-folder-id", | ||
| "folder_path": "/restricted/folder/path", | ||
| } | ||
|
|
||
| response = client.post("/folders/sync-folder", json=request_data) | ||
|
|
||
| assert response.status_code == 401 | ||
| data = response.json() | ||
| assert data["detail"]["success"] is False | ||
| assert data["detail"]["error"] == "Permission denied" | ||
|
|
||
| @patch("app.utils.folders.os.listdir") | ||
| def test_sync_folder_not_a_directory_returns_404( | ||
| self, mock_listdir: MagicMock, client: TestClient | ||
| ) -> None: | ||
| """Test syncing a folder which is not directory returns 404.""" | ||
| mock_listdir.side_effect = NotADirectoryError("Not A Directory") | ||
|
|
||
| request_data = { | ||
| "folder_id": "dummy-folder-id", | ||
| "folder_path": "/path/to/some/file.txt", | ||
| } | ||
|
|
||
| response = client.post("/folders/sync-folder", json=request_data) | ||
|
|
||
| assert response.status_code == 404 | ||
| data = response.json() | ||
| assert data["detail"]["success"] is False | ||
| assert data["detail"]["error"] == "Folder not found" | ||
|
|
||
| @patch("app.routes.folders.post_sync_folder_sequence") | ||
| def test_sync_folder_success( | ||
| self, mock_post_sync: MagicMock, client: TestClient | ||
| ) -> None: | ||
| """Test successfully syncing an existing folder.""" | ||
| with tempfile.TemporaryDirectory() as tmpdir: | ||
| subfolder = os.path.join(tmpdir, "subfolder1") | ||
| os.makedirs(subfolder) | ||
|
|
||
| request_data = { | ||
| "folder_id": "test-sync-id", | ||
| "folder_path": tmpdir, | ||
| } | ||
|
|
||
| response = client.post("/folders/sync-folder", json=request_data) | ||
|
|
||
| assert response.status_code == 200 | ||
| data = response.json() | ||
| assert data["success"] is True | ||
| assert data["data"]["folder_id"] == "test-sync-id" | ||
| assert data["data"]["folder_path"] == tmpdir | ||
|
|
||
|
Comment on lines
+977
to
+997
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This function is writing a real orphan folder row into the test database... non-blocking but better to mock instead. |
||
| # ============================================================================ | ||
| # Unit Tests | ||
| # ============================================================================ | ||
|
|
@@ -1443,11 +1584,16 @@ def mock_find_parent_side_effect(folder_path): | |
|
|
||
| assert mock_find_parent.call_count >= 1 | ||
|
|
||
| @patch("app.routes.folders.API_util_restart_sync_microservice_watcher") | ||
| @patch("app.routes.folders.db_delete_folders_batch") | ||
| @patch("app.routes.folders.db_enable_ai_tagging_batch") | ||
| def test_complete_folder_lifecycle( | ||
| self, mock_enable_batch, mock_delete_batch, client | ||
| ): | ||
| self, | ||
| mock_enable_batch: MagicMock, | ||
| mock_delete_batch: MagicMock, | ||
| mock_restart_watcher: MagicMock, | ||
| client: TestClient, | ||
| ) -> None: | ||
| """Test complete folder lifecycle: enable AI -> delete.""" | ||
| folder_ids = ["folder-1", "folder-2"] | ||
|
|
||
|
|
@@ -1470,3 +1616,4 @@ def test_complete_folder_lifecycle( | |
|
|
||
| mock_enable_batch.assert_called_once_with(folder_ids) | ||
| mock_delete_batch.assert_called_once_with(folder_ids) | ||
| mock_restart_watcher.assert_called_once() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@rohan-pandeyy, the changes have been validated by me, the co-author doesn't see any issues with the changes on their end too, do lmk if any changes needed
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the restart is called inline, it becomes a loop. the watched thread waits for
delete-folders, and the backend waits forPOST watcher/restartand the restart waits for that same blocked thread.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
deletion of a folder has gone from instant to 5 seconds.