From fe7cabd7959dc15bbb1d4307ecbd17184fbebfa9 Mon Sep 17 00:00:00 2001 From: lkk Date: Thu, 3 Dec 2026 18:31:22 +0800 Subject: [PATCH] fix(knowledge): keep the newest publish card and soft-delete the old one A repeated merge should leave the latest publish entry as the only valid entrance. The previous card stays listed as superseded, and deleting it only sets a delete time so it never enters the recycle bin. Co-authored-by: Cursor --- ...knowledge_document_distribution_service.py | 174 +++++++++++++++--- .../services/knowledge_space_service.py | 62 +++++-- ...knowledge_document_distribution_publish.py | 57 +++++- .../test_superseded_publish_reason.py | 70 +++++++ .../pages/knowledge/SpaceDetail/FileCard.tsx | 4 +- .../pages/knowledge/SpaceDetail/FileTable.tsx | 4 +- .../portal/PortalKnowledgeWorkbench.test.tsx | 42 +++++ 7 files changed, 361 insertions(+), 52 deletions(-) create mode 100644 src/backend/test/knowledge/test_superseded_publish_reason.py diff --git a/src/backend/bisheng/knowledge/domain/services/knowledge_document_distribution_service.py b/src/backend/bisheng/knowledge/domain/services/knowledge_document_distribution_service.py index bc093973ae..f1b51b7305 100644 --- a/src/backend/bisheng/knowledge/domain/services/knowledge_document_distribution_service.py +++ b/src/backend/bisheng/knowledge/domain/services/knowledge_document_distribution_service.py @@ -770,6 +770,81 @@ async def _append_publish_to_predecessor_chain( self.session.add(document) self.session.add(new_publish) + async def _retire_same_space_publish_for_new_head( + self, + document: KnowledgeDocument, + new_publish: KnowledgeFile, + ) -> None: + """Make the newest same-space publish the rollback head and retire the previous card. + + The retired card stays listed as invalid until the user soft-deletes it. + Its permissions and the canonical document stay in place. + """ + entries = await self.file_repository.find_distribution_entries_by_document_id( + int(document.id), + for_update=True, + ) + same_space = [ + entry + for entry in entries + if int(entry.id) != int(new_publish.id) + and int(entry.knowledge_id) == int(new_publish.knowledge_id) + and entry.entry_type == KnowledgeFileEntryType.PUBLISH.value + and entry.entry_status == KnowledgeFileEntryStatus.ACTIVE.value + and entry.deleted_at is None + ] + if not same_space: + return + pointing = [ + entry + for entry in entries + if int(entry.id) != int(new_publish.id) and int(entry.predecessor_logic_file_id or 0) == int(new_publish.id) + ] + if len(pointing) != 1: + raise KnowledgeDocumentDistributionError("publish predecessor chain is ambiguous") + previous_head_id = document.predecessor_logic_file_id + pointing[0].predecessor_logic_file_id = None + new_publish.predecessor_logic_file_id = previous_head_id + document.predecessor_logic_file_id = int(new_publish.id) + for old in same_space: + old.entry_status = KnowledgeFileEntryStatus.INVALID.value + old.projection_status = KnowledgeFileProjectionStatus.READY.value + old.projection_next_retry_at = None + self.session.add(old) + self.session.add(pointing[0]) + self.session.add(new_publish) + self.session.add(document) + await self.session.flush() + self._active_publish_predecessor(document, entries) + await self._request_publish_fulltext_delete(same_space) + + async def _request_publish_fulltext_delete(self, entries: Sequence[KnowledgeFile]) -> None: + if not entries: + return + try: + from bisheng.knowledge.domain.services.knowledge_fulltext_lifecycle_hook import ( + KnowledgeFulltextFileRef, + request_file_delete_intents, + ) + + await request_file_delete_intents( + self.session, + [ + KnowledgeFulltextFileRef( + file_id=int(entry.id), + knowledge_id=int(entry.knowledge_id), + tenant_id=int(entry.tenant_id or 1), + ) + for entry in entries + ], + trigger_type="superseded_publish_retired", + ) + except Exception: + logger.exception( + "fulltext delete intent failed for superseded publish entries=%s", + [int(entry.id) for entry in entries], + ) + async def attach_existing_as_publish( self, command: AttachExistingAsPublishCommand, @@ -2338,28 +2413,7 @@ async def _activate_publish_merge( self.session.add(target_document) await self.session.flush() await self._append_publish_to_predecessor_chain(target_document, publish) - same_space_publish = next( - ( - entry - for entry in await self.file_repository.find_distribution_entries_by_document_id( - int(target_document.id), - for_update=True, - ) - if int(entry.id) != int(publish.id) - and int(entry.knowledge_id) == int(publish.knowledge_id) - and entry.entry_type == KnowledgeFileEntryType.PUBLISH.value - and entry.entry_status == KnowledgeFileEntryStatus.ACTIVE.value - ), - None, - ) - if same_space_publish is not None: - # The source space already shows this document through an older publish - # entry. Keep that visible row and retain the approval entry only for retry. - publish.entry_status = KnowledgeFileEntryStatus.INVALID.value - publish.projection_status = KnowledgeFileProjectionStatus.READY.value - publish.projection_next_retry_at = None - self.session.add(publish) - await self.session.flush() + await self._retire_same_space_publish_for_new_head(target_document, publish) organization_service = KnowledgeFileOrganizationService(self.session) await organization_service.repository.set_document_organization( int(target_document.id), command.tenant_id, target_old_manager.belonging_organization_id @@ -3068,6 +3122,61 @@ async def force_detach_publish_entry( document_pointer_moved=document_pointer_moved, ) + async def _soft_delete_superseded_publish( + self, + document: KnowledgeDocument, + entry: KnowledgeFile, + ) -> RemoveShareEntryResult: + """Hide a retired publish card without putting it in the recycle bin. + + The row stays so favorites and chat citations can still find the document + and open the current publish card. Only this card's permissions are revoked. + """ + entries = await self.file_repository.find_distribution_entries_by_document_id( + int(document.id), + for_update=True, + ) + successor_id = entry.predecessor_logic_file_id + for other in entries: + if int(other.id) == int(entry.id): + continue + if int(other.predecessor_logic_file_id or 0) == int(entry.id): + other.predecessor_logic_file_id = successor_id + self.session.add(other) + if int(document.predecessor_logic_file_id or 0) == int(entry.id): + document.predecessor_logic_file_id = successor_id + self.session.add(document) + self._active_publish_predecessor( + document, + [other for other in entries if int(other.id) != int(entry.id)], + ) + entry.deleted_at = datetime.now() + self.session.add(entry) + await self.session.flush() + await self._request_publish_fulltext_delete([entry]) + await self._commit() + try: + explicit_snapshot = list(await self.permission_snapshot_loader(int(entry.id))) + operations = [ + self.permission_activation_service.build_parent_operation(entry, action="delete"), + *self.permission_activation_service._normalize_operations( + explicit_snapshot, + action="delete", + ), + ] + await self.permission_activation_service.tuple_writer(operations) + except Exception: + logger.exception( + "superseded publish permission revoke deferred: entry_id=%s", + entry.id, + ) + await self._enqueue_content_stat_files([int(entry.id)]) + return RemoveShareEntryResult( + document_id=int(document.id), + share_entry_id=int(entry.id), + idempotent=False, + ) + async def remove_invalid_entry( self, *, @@ -3083,11 +3192,6 @@ async def remove_invalid_entry( int(document.tenant_id or 0) != tenant_id or int(entry.tenant_id or 0) != tenant_id or int(entry.reference_document_id or 0) != document_id - or document.lifecycle_status - not in { - KnowledgeDocumentLifecycleStatus.DELETING.value, - KnowledgeDocumentLifecycleStatus.INVALID.value, - } or entry.entry_status != KnowledgeFileEntryStatus.INVALID.value or entry.entry_type not in { @@ -3096,6 +3200,22 @@ async def remove_invalid_entry( } ): raise KnowledgeDocumentDistributionError("entry is not an invalid distribution tombstone") + if entry.deleted_at is not None: + return RemoveShareEntryResult( + document_id=document_id, + share_entry_id=entry_id, + idempotent=True, + ) + if ( + document.lifecycle_status == KnowledgeDocumentLifecycleStatus.ACTIVE.value + and entry.entry_type == KnowledgeFileEntryType.PUBLISH.value + ): + return await self._soft_delete_superseded_publish(document, entry) + if document.lifecycle_status not in { + KnowledgeDocumentLifecycleStatus.DELETING.value, + KnowledgeDocumentLifecycleStatus.INVALID.value, + }: + raise KnowledgeDocumentDistributionError("entry is not an invalid distribution tombstone") entry.entry_status = KnowledgeFileEntryStatus.DELETING.value entry.desired_entry_generation = int(entry.desired_entry_generation or 0) + 1 entry.projection_status = KnowledgeFileProjectionStatus.PENDING.value diff --git a/src/backend/bisheng/knowledge/domain/services/knowledge_space_service.py b/src/backend/bisheng/knowledge/domain/services/knowledge_space_service.py index fe218b3613..056d417968 100644 --- a/src/backend/bisheng/knowledge/domain/services/knowledge_space_service.py +++ b/src/backend/bisheng/knowledge/domain/services/knowledge_space_service.py @@ -1185,13 +1185,34 @@ async def _resolve_document_entry( file_id=int(file_record.id), ) except KnowledgeDocumentEntryResolutionError as exc: - raise SpaceFileNotFoundError() from exc + resolved = await self._resolve_replaced_publish_entry(file_record) + if resolved is None: + raise SpaceFileNotFoundError() from exc if required_capability and not bool(getattr(resolved.capabilities, required_capability, False)): if required_capability == "can_download": raise KnowledgeDocumentDownloadDeniedError() raise SpacePermissionDeniedError() return resolved + async def _resolve_replaced_publish_entry(self, file_record: KnowledgeFile): + """Open the current publish card when a stored id points at a retired one.""" + durable = getattr(self, "document_durable_reference_resolver", None) + if durable is None: + return None + from bisheng.knowledge.domain.services.knowledge_document_entry_resolver import ( + KnowledgeDocumentEntryResolutionError, + ) + + try: + return await durable.resolve( + tenant_id=int(self.login_user.tenant_id), + requested_space_id=int(file_record.knowledge_id), + durable_file_id=int(file_record.id), + require_view_permission=True, + ) + except KnowledgeDocumentEntryResolutionError: + return None + async def _resolve_shougang_portal_content_entry( self, file_record: KnowledgeFile, @@ -15578,6 +15599,28 @@ async def _load_document_distribution_info( canonical_version_id = None manager_file_id = None manager_space_id = None + if ( + is_invalid + and document is not None + and document.lifecycle_status == KnowledgeDocumentLifecycleStatus.ACTIVE.value + and entry_type == KnowledgeFileEntryType.PUBLISH.value + ): + distribution_invalid_reason = "superseded_by_newer_publish" + elif ( + is_invalid + and document is not None + and document.lifecycle_status + in { + KnowledgeDocumentLifecycleStatus.DELETING.value, + KnowledgeDocumentLifecycleStatus.INVALID.value, + } + and distribution_space_state_map.get(int(document.knowledge_id)) == KnowledgeState.PUBLISHED.value + ): + distribution_invalid_reason = "manager_file_deleted" + elif is_invalid: + distribution_invalid_reason = "manager_space_deleted" + else: + distribution_invalid_reason = None is_distribution = item.reference_document_id is not None projection_ready = ( item.projection_status == KnowledgeFileProjectionStatus.READY.value @@ -15596,22 +15639,7 @@ async def _load_document_distribution_info( "canonical_version_id": canonical_version_id, "manager_file_id": manager_file_id, "manager_space_id": manager_space_id, - "distribution_invalid_reason": ( - ( - "manager_file_deleted" - if document is not None - and document.lifecycle_status - in { - KnowledgeDocumentLifecycleStatus.DELETING.value, - KnowledgeDocumentLifecycleStatus.INVALID.value, - } - and distribution_space_state_map.get(int(document.knowledge_id)) - == KnowledgeState.PUBLISHED.value - else "manager_space_deleted" - ) - if is_invalid - else None - ), + "distribution_invalid_reason": distribution_invalid_reason, "desired_content_generation": (int(item.desired_content_generation) if is_distribution else 0), "applied_content_generation": (int(item.applied_content_generation) if is_distribution else 0), "desired_entry_generation": (int(item.desired_entry_generation) if is_distribution else 0), diff --git a/src/backend/test/knowledge/test_knowledge_document_distribution_publish.py b/src/backend/test/knowledge/test_knowledge_document_distribution_publish.py index a809b71c98..917a29d272 100644 --- a/src/backend/test/knowledge/test_knowledge_document_distribution_publish.py +++ b/src/backend/test/knowledge/test_knowledge_document_distribution_publish.py @@ -1254,7 +1254,7 @@ async def test_publish_merge_rejects_distributed_target( async def test_publish_merge_keeps_existing_source_space_publish_entry( async_db_session: AsyncSession, ): - """A similar document that was already published keeps one visible source entry.""" + """A repeated merge keeps the newest source card and retires the previous one.""" await _seed_manager(async_db_session) source_versions = await KnowledgeDocumentVersionRepositoryImpl(async_db_session).find_by_document_id(91) await async_db_session.delete(source_versions[0]) @@ -1327,19 +1327,64 @@ async def test_publish_merge_keeps_existing_source_space_publish_entry( ] assert await document_repository.find_by_id(91) is None - assert target_document.predecessor_logic_file_id == 201 + assert target_document.predecessor_logic_file_id == approval_publish.id assert target_document.primary_version_id == 501 - assert existing_publish.predecessor_logic_file_id == approval_publish.id - assert existing_publish.entry_status == KnowledgeFileEntryStatus.ACTIVE.value - assert approval_publish.entry_status == KnowledgeFileEntryStatus.INVALID.value + assert target_document.lifecycle_status == "active" + assert approval_publish.predecessor_logic_file_id == 201 + assert approval_publish.entry_status == KnowledgeFileEntryStatus.ACTIVE.value + assert approval_publish.deleted_at is None + assert existing_publish.entry_status == KnowledgeFileEntryStatus.INVALID.value + assert existing_publish.deleted_at is None + assert existing_publish.predecessor_logic_file_id is None assert approval_publish.knowledge_id == 10 assert manager.knowledge_id == 20 assert manager.reference_document_id == 92 assert manager.entry_type == KnowledgeFileEntryType.MANAGER.value - assert [int(entry.id) for entry in visible_publishes] == [201] + assert [int(entry.id) for entry in visible_publishes] == [int(approval_publish.id)] assert second.idempotent is True assert second.document_id == 92 + from bisheng.knowledge.domain.services.knowledge_document_entry_resolver import ( + KnowledgeDocumentDurableReferenceResolver, + KnowledgeDocumentEntryResolver, + ) + + async def allow_view(_file_id: int, _space_id: int) -> set[str]: + return {"view_file"} + + entry_resolver = KnowledgeDocumentEntryResolver( + document_repository=document_repository, + version_repository=KnowledgeDocumentVersionRepositoryImpl(async_db_session), + file_repository=file_repository, + permission_loader=allow_view, + ) + durable = KnowledgeDocumentDurableReferenceResolver( + entry_resolver=entry_resolver, + version_repository=KnowledgeDocumentVersionRepositoryImpl(async_db_session), + file_repository=file_repository, + ) + opened = await durable.resolve(tenant_id=7, requested_space_id=10, durable_file_id=201) + assert opened.entry_file_id == int(approval_publish.id) + + removed = await service.remove_invalid_entry(tenant_id=7, document_id=92, entry_id=201) + again = await service.remove_invalid_entry(tenant_id=7, document_id=92, entry_id=201) + retired = await file_repository.find_by_id(201) + current = await file_repository.find_by_id(int(approval_publish.id)) + target_document = await document_repository.find_by_id(92) + + assert removed.idempotent is False + assert again.idempotent is True + assert retired is not None + assert retired.deleted_at is not None + assert retired.entry_status == KnowledgeFileEntryStatus.INVALID.value + assert current.entry_status == KnowledgeFileEntryStatus.ACTIVE.value + assert current.deleted_at is None + assert current.predecessor_logic_file_id is None + assert target_document.predecessor_logic_file_id == int(approval_publish.id) + assert target_document.lifecycle_status == "active" + opened_after_delete = await durable.resolve(tenant_id=7, requested_space_id=10, durable_file_id=201) + assert opened_after_delete.entry_file_id == int(approval_publish.id) + @pytest.mark.asyncio async def test_publish_merge_rejects_duplicate_current_target_content( diff --git a/src/backend/test/knowledge/test_superseded_publish_reason.py b/src/backend/test/knowledge/test_superseded_publish_reason.py new file mode 100644 index 0000000000..b357806d9d --- /dev/null +++ b/src/backend/test/knowledge/test_superseded_publish_reason.py @@ -0,0 +1,70 @@ +"""Invalid publish cards of a living document use a distinct list reason.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock, patch + +import pytest + +from bisheng.knowledge.domain.models.knowledge import KnowledgeState +from bisheng.knowledge.domain.models.knowledge_file import FileType +from bisheng.knowledge.domain.services.knowledge_space_service import KnowledgeSpaceService + + +def _service() -> KnowledgeSpaceService: + service = KnowledgeSpaceService.__new__(KnowledgeSpaceService) + service._load_folder_stat_counts = AsyncMock(return_value={}) + service._load_file_tags_batch = AsyncMock(return_value={}) + service.doc_repo = None + service.version_repo = None + service._entry_permission_ids_by_file = {9001: {"delete_file"}} + service.get_logo_share_link = Mock(return_value="thumb") + return service + + +def _publish_card(): + file = Mock() + file.file_type = FileType.FILE + file.id = 9001 + file.thumbnails = "" + file.abstract = "" + file.similar_status = 0 + file.reference_document_id = 501 + file.entry_type = "publish" + file.entry_status = "invalid" + file.original_uploader_id = None + file.original_knowledge_id = None + file.allow_download = False + file.knowledge_id = 10 + file.desired_content_generation = 1 + file.applied_content_generation = 1 + file.desired_entry_generation = 1 + file.applied_entry_generation = 1 + file.projection_status = "ready" + file.model_dump.return_value = {"id": 9001, "file_name": "old.doc", "file_type": FileType.FILE.value} + return file + + +@pytest.mark.asyncio +async def test_invalid_publish_of_active_document_is_superseded(): + service = _service() + service.doc_repo = SimpleNamespace( + find_by_ids=AsyncMock( + return_value=[ + SimpleNamespace( + id=501, + knowledge_id=10, + primary_version_id=None, + lifecycle_status="active", + ) + ] + ) + ) + + with patch( + "bisheng.knowledge.domain.services.knowledge_space_service.KnowledgeDao.async_get_spaces_by_ids", + new_callable=AsyncMock, + return_value=[SimpleNamespace(id=10, name="target", state=KnowledgeState.PUBLISHED.value)], + ): + result = await service._load_document_distribution_info([_publish_card()]) + + assert result[9001]["distribution_invalid_reason"] == "superseded_by_newer_publish" diff --git a/src/frontend/client/src/pages/knowledge/SpaceDetail/FileCard.tsx b/src/frontend/client/src/pages/knowledge/SpaceDetail/FileCard.tsx index e9cf5c12f1..0bda543efa 100644 --- a/src/frontend/client/src/pages/knowledge/SpaceDetail/FileCard.tsx +++ b/src/frontend/client/src/pages/knowledge/SpaceDetail/FileCard.tsx @@ -274,7 +274,9 @@ export function FileCard({ {file.entryStatus === "invalid" ? file.distributionInvalidReason === "manager_file_deleted" ? "已失效:原文件已删除" - : "已失效:原管理知识库已删除" + : file.distributionInvalidReason === "superseded_by_newer_publish" + ? "已失效:已被新的发布替代" + : "已失效:原管理知识库已删除" : file.entryType === "manager" ? "管理文件" : file.entryType === "publish" diff --git a/src/frontend/client/src/pages/knowledge/SpaceDetail/FileTable.tsx b/src/frontend/client/src/pages/knowledge/SpaceDetail/FileTable.tsx index 256a481881..3d8242a3c9 100644 --- a/src/frontend/client/src/pages/knowledge/SpaceDetail/FileTable.tsx +++ b/src/frontend/client/src/pages/knowledge/SpaceDetail/FileTable.tsx @@ -1553,7 +1553,9 @@ function FileRow({ {file.entryStatus === "invalid" ? file.distributionInvalidReason === "manager_file_deleted" ? "已失效:原文件已删除" - : "已失效:原管理知识库已删除" + : file.distributionInvalidReason === "superseded_by_newer_publish" + ? "已失效:已被新的发布替代" + : "已失效:原管理知识库已删除" : file.entryType === "manager" ? "管理文件" : file.entryType === "publish" diff --git a/src/frontend/client/src/pages/knowledge/portal/PortalKnowledgeWorkbench.test.tsx b/src/frontend/client/src/pages/knowledge/portal/PortalKnowledgeWorkbench.test.tsx index 905caade95..d530b1a1ed 100644 --- a/src/frontend/client/src/pages/knowledge/portal/PortalKnowledgeWorkbench.test.tsx +++ b/src/frontend/client/src/pages/knowledge/portal/PortalKnowledgeWorkbench.test.tsx @@ -3303,6 +3303,48 @@ describe("PortalKnowledgeWorkbench", () => { expect(within(row).getByText("已失效:原文件已删除")).toBeInTheDocument(); }); + test("再次发布留下的旧卡片显示已被新发布替代", async () => { + const personalSpace = makeSpace("personal-superseded", "个人知识库", { + role: SpaceRole.ADMIN, + spaceLevel: SpaceLevel.DEPARTMENT, + }); + const invalidFile = makeFile("321", "报告.doc", { + type: FileType.PDF, + spaceId: personalSpace.id, + entryType: "publish", + entryStatus: "invalid", + distributionInvalidReason: "superseded_by_newer_publish", + capabilities: { + canView: false, + canPreview: false, + canDownload: false, + canMove: false, + canManageMembers: false, + canEditContent: false, + canPublish: false, + canShare: false, + canDelete: true, + }, + }); + jest.mocked(getGroupedSpacesApi).mockResolvedValue({ + publicSpaces: [], + departmentSpaces: [personalSpace], + teamSpaces: [], + personalSpaces: [], + } as any); + jest.mocked(getSpaceChildrenApi).mockResolvedValue({ + data: [invalidFile], + page_size: 20, + has_more: false, + next_cursor: null, + }); + jest.mocked(getSpaceInfoApi).mockResolvedValue(personalSpace as any); + + renderWorkbench(`/knowledge-portal?spaceId=${personalSpace.id}`); + + expect(await screen.findByText("已失效:已被新的发布替代")).toBeInTheDocument(); + }); + test("keeps share deletion hidden when the live delete permission is denied", async () => { const favoriteSpace = makeDefaultFavoriteSpace(); const departmentSpace = makeSpace("department-delete-denied", "接收知识库", {