Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions openrag/components/indexer/indexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,19 @@ async def update_file_metadata(
for doc in docs:
doc.metadata.update(metadata)

# Snapshot workspace memberships before deletion so they can be restored.
workspace_ids = await vectordb.get_file_workspaces.remote(file_id, partition)

await self.delete_file(file_id, partition)
await vectordb.async_add_documents.remote(docs, user=user)

# Restore workspace memberships that existed before the delete.
if workspace_ids:
await asyncio.gather(
*[vectordb.add_files_to_workspace.remote(ws_id, [file_id]) for ws_id in workspace_ids]
)
log.debug("Restored workspace memberships after metadata update.", workspace_ids=workspace_ids)
Comment on lines +198 to +209

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard workspace restoration on partition moves, and keep it best-effort.

workspace_ids here are captured from the original partition, but openrag/routers/indexer.py Lines 339-346 allow PATCH to move the file to a different partition. Re-adding those IDs on Lines 205-208 would recreate workspace_files rows for workspaces that still belong to the old partition, and any exception here currently makes the PATCH fail after the file has already been reindexed successfully.

Proposed fix
             # Snapshot workspace memberships before deletion so they can be restored.
             workspace_ids = await vectordb.get_file_workspaces.remote(file_id, partition)

             await self.delete_file(file_id, partition)
             await vectordb.async_add_documents.remote(docs, user=user)

             # Restore workspace memberships that existed before the delete.
-            if workspace_ids:
-                await asyncio.gather(
-                    *[vectordb.add_files_to_workspace.remote(ws_id, [file_id]) for ws_id in workspace_ids]
-                )
-                log.debug("Restored workspace memberships after metadata update.", workspace_ids=workspace_ids)
+            target_partition = metadata.get("partition", partition)
+            if workspace_ids and target_partition == partition:
+                try:
+                    await asyncio.gather(
+                        *[vectordb.add_files_to_workspace.remote(ws_id, [file_id]) for ws_id in workspace_ids]
+                    )
+                    log.debug(
+                        "Restored workspace memberships after metadata update.",
+                        workspace_ids=workspace_ids,
+                    )
+                except Exception as ws_err:
+                    log.warning(
+                        "Failed to restore workspace memberships after metadata update.",
+                        error=str(ws_err),
+                        workspace_ids=workspace_ids,
+                    )
+            elif workspace_ids:
+                log.info(
+                    "Skipping workspace restoration because the file moved to a different partition.",
+                    old_partition=partition,
+                    new_partition=target_partition,
+                    workspace_ids=workspace_ids,
+                )

Based on learnings: workspace association is a best-effort metadata step and failures should be logged without turning a successfully indexed file into a failed operation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openrag/components/indexer/indexer.py` around lines 198 - 209, Capture
workspace_ids from the original partition as before but, before re-adding, fetch
the file's current partition (e.g., via vectordb.get_file or a
get_file_partition helper) and only attempt restoration if the current partition
still equals the original partition; wrap the restore loop that calls
vectordb.add_files_to_workspace.remote(...) in a try/except so any exception is
logged as a warning/debug and swallowed (best-effort) so a successful reindex
does not fail; keep using the existing symbols workspace_ids, file_id,
partition, vectordb.get_file_workspaces, vectordb.add_files_to_workspace and the
surrounding delete_file/async_add_documents flow.


log.info("Metadata updated for file.")
except Exception as e:
log.error("Error in update_file_metadata", error=str(e))
Expand Down
12 changes: 12 additions & 0 deletions openrag/components/indexer/vectordb/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,18 @@ def list_workspace_files(self, workspace_id: str) -> list[str]:
result = session.execute(select(WorkspaceFile.file_id).where(WorkspaceFile.workspace_id == workspace_id))
return [r[0] for r in result.all()]

def get_file_workspaces(self, file_id: str, partition: str) -> list[str]:
"""Return the workspace IDs that contain the given file, scoped to the given partition."""
with self.Session() as session:
ws_ids = select(Workspace.workspace_id).where(Workspace.partition_name == partition)
result = session.execute(
select(WorkspaceFile.workspace_id).where(
WorkspaceFile.file_id == file_id,
WorkspaceFile.workspace_id.in_(ws_ids),
)
)
return [r[0] for r in result.all()]

def remove_file_from_all_workspaces(self, file_id: str, partition: str):
"""Remove file from all workspaces in the given partition — called during file deletion."""
with self.Session() as session:
Expand Down
4 changes: 4 additions & 0 deletions openrag/components/indexer/vectordb/vectordb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,10 @@ async def remove_file_from_workspace(self, workspace_id: str, file_id: str) -> b
async def list_workspace_files(self, workspace_id: str) -> list[str]:
return self.partition_file_manager.list_workspace_files(workspace_id)

async def get_file_workspaces(self, file_id: str, partition: str) -> list[str]:
"""Return workspace IDs that contain the given file, scoped to the partition."""
return self.partition_file_manager.get_file_workspaces(file_id, partition)


def _gen_chunk_order_metadata(n: int = 20) -> list[dict]:
# Use base timestamp + index to ensure uniqueness
Expand Down
13 changes: 11 additions & 2 deletions openrag/routers/indexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,9 @@ async def put_file(
detail=f"'{file_id}' not found in partition '{partition}'",
)

# Snapshot workspace memberships before deletion so they can be restored on the new version.
existing_workspace_ids = await vectordb.get_file_workspaces.remote(file_id, partition)

# Delete the existing file from the vector database
await indexer.delete_file.remote(file_id, partition)

Expand All @@ -288,8 +291,14 @@ async def put_file(
metadata["created_at"] = datetime.fromtimestamp(file_stat.st_ctime).isoformat()
metadata["file_id"] = file_id

# Indexing the file
task = indexer.add_file.remote(path=file_path, metadata=metadata, partition=partition, user=user)
# Indexing the file — restore pre-existing workspace memberships on the new version.
task = indexer.add_file.remote(
path=file_path,
metadata=metadata,
partition=partition,
user=user,
workspace_ids=existing_workspace_ids or None,
)
await task_state_manager.set_state.remote(task.task_id().hex(), "QUEUED")
await task_state_manager.set_object_ref.remote(task.task_id().hex(), {"ref": task})

Expand Down
Loading