Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
*,
Expand All @@ -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 {
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading