diff --git a/backend/app/gateway/routers/threads.py b/backend/app/gateway/routers/threads.py index 89ae8030d3..7fdaea2379 100644 --- a/backend/app/gateway/routers/threads.py +++ b/backend/app/gateway/routers/threads.py @@ -49,6 +49,7 @@ from app.gateway.history_seed import reserve_history_seed, write_history_seed from app.gateway.hitl_approval import find_pending_interrupts from app.gateway.internal_auth import get_trusted_internal_owner_user_id from app.gateway.services import ( + _THREAD_METADATA_SETUP_TIMEOUT_SECONDS, abuild_checkpoint_state_accessor, build_checkpoint_state_mutation_accessor, build_thread_checkpoint_state_accessor, @@ -57,7 +58,7 @@ from app.gateway.services import ( reserve_checkpoint_write, strip_server_owned_state_metadata, ) -from app.gateway.share_fork import SHARE_IMPORT_COMPLETE_KEY, SHARE_IMPORT_HISTORY_MARKED_KEY +from app.gateway.share_fork import SHARE_IMPORT_COMPLETE_KEY, SHARE_IMPORT_HISTORY_MARKED_KEY, branch_share_provenance, mark_imported, prepare_share_copy_compaction from app.gateway.utils import sanitize_log_param from deerflow.agents.human_input import extract_unanswered_human_input_request from deerflow.agents.thread_state import THREAD_STATE_REDUCER_FIELDS @@ -102,6 +103,7 @@ from deerflow.runtime.serialization import serialize_lc_object from deerflow.runtime.user_context import get_effective_user_id from deerflow.uploads.companions import register_companion, resolve_companion from deerflow.utils.file_io import await_drained, run_file_io +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL from deerflow.utils.thread_id import ThreadId, resolve_thread_id, validate_thread_id from deerflow.utils.time import coerce_iso, now_iso @@ -1179,6 +1181,9 @@ async def _branch_thread_with_reservation( snapshot, target_human_id, ) + # A copy imported before share provenance moved into state has nothing for + # the branch to inherit, so the branch gets it from the source's import. + branch_provenance = await branch_share_provenance(request, source_metadata, snapshot.values, source_accessor, source_config) # Workspace files are not checkpointed, so they only reflect the *current* thread # state. Cloning them onto a branch from an older turn would leak files created @@ -1243,10 +1248,14 @@ async def _branch_thread_with_reservation( for key, value in source_values.items(): if key in _BRANCH_EXCLUDED_CHANNELS: continue + if key == "messages" and isinstance(value, list) and branch_provenance is not None: + value = mark_imported(value, branch_provenance[1]) if key in branch_reducer_fields: values[key] = Overwrite(list(value) if key == "messages" and isinstance(value, list) else value) else: values[key] = value + if branch_provenance is not None: + values[IMPORTED_HISTORY_CHANNEL] = branch_provenance[0] if replaces is not None: # The head write lands on the replay base, so goal state the head # lacks (write_thread_goal pops goal and goal_outcome) would keep @@ -1800,6 +1809,9 @@ async def compact_thread(thread_id: ThreadId, body: ThreadCompactRequest, reques keep = body.keep.to_tuple() if body.keep is not None else None try: async with reserve_checkpoint_write(request, thread_id, user_id=get_effective_user_id()): + # Migrate an older share copy under this reservation before its + # copied turns can reach the memory flush. + memory_flush = await prepare_share_copy_compaction(request, thread_id, accessor, read_config, as_node="manual_compaction", metadata_timeout=_THREAD_METADATA_SETUP_TIMEOUT_SECONDS) result = await compact_thread_context( accessor, thread_id, @@ -1808,6 +1820,7 @@ async def compact_thread(thread_id: ThreadId, body: ThreadCompactRequest, reques user_id=get_effective_user_id(), agent_name=body.agent_name, model_name=body.model_name, + memory_flush=memory_flush, ) except ConflictError: raise HTTPException(status_code=409, detail="Thread has a run in flight. Compact after the run finishes.") from None diff --git a/backend/app/gateway/services.py b/backend/app/gateway/services.py index 27c5582f9d..8f398038ad 100644 --- a/backend/app/gateway/services.py +++ b/backend/app/gateway/services.py @@ -117,7 +117,7 @@ from deerflow.trace_context import DEERFLOW_TRACE_METADATA_KEY, ensure_trace_con from deerflow.utils.assembly_io import run_assembly from deerflow.utils.file_io import await_drained from deerflow.utils.goal_objective import normalize_goal_objective -from deerflow.utils.messages import IMPORTED_HISTORY_KEY, ORIGINAL_USER_CONTENT_KEY, UNTRUSTED_INPUT_KEY +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY, ORIGINAL_USER_CONTENT_KEY, UNTRUSTED_INPUT_KEY from deerflow.utils.thread_id import validate_thread_id logger = logging.getLogger(__name__) @@ -650,7 +650,7 @@ def _normalize_input_messages( #: record that clearing a satisfied goal writes; a caller copy would forge one. #: Older checkpoints can contain loop detection's record of frequency-capped #: tools. Reserve its channel for server-owned state. -SERVER_OWNED_STATE_CHANNELS = frozenset({"sandbox", "thread_data", "viewed_images", "goal_outcome", "applied_run_inputs", LOOP_CAP_STATE_KEY}) +SERVER_OWNED_STATE_CHANNELS = frozenset({"sandbox", "thread_data", "viewed_images", "goal_outcome", "applied_run_inputs", LOOP_CAP_STATE_KEY, IMPORTED_HISTORY_CHANNEL}) #: The ``write_todos`` status contract the todo middleware renders. _TODO_STATUSES = frozenset({"pending", "in_progress", "completed", "blocked", "waiting"}) diff --git a/backend/app/gateway/share_fork.py b/backend/app/gateway/share_fork.py index 0ee5148c01..626bd189b2 100644 --- a/backend/app/gateway/share_fork.py +++ b/backend/app/gateway/share_fork.py @@ -4,6 +4,7 @@ import asyncio import logging import os import uuid +from collections.abc import Mapping from contextlib import asynccontextmanager from deerflow_extension_api import AgentRunError @@ -23,19 +24,22 @@ from deerflow.config.paths import get_paths from deerflow.persistence.thread_meta import ThreadMetaStore from deerflow.persistence.thread_shares.sql import ThreadShareRepository from deerflow.runtime import ConflictError, ThreadOperationKind +from deerflow.runtime.context_keys import checkpoint_agent_binding_metadata from deerflow.runtime.events.store.db import DbRunEventStore from deerflow.runtime.goal import goal_thread_lock from deerflow.runtime.journal import build_branch_history_seed_events from deerflow.runtime.user_context import get_effective_user_id from deerflow.sandbox.artifact_snapshot import publish_snapshot from deerflow.utils.file_io import run_file_io -from deerflow.utils.messages import IMPORTED_HISTORY_KEY +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY, IMPORTED_HISTORY_UNRESOLVED logger = logging.getLogger(__name__) #: Thread metadata, written only by this module (the thread routes strip #: client copies): the copy's history is fully imported, and its copied -#: messages carry :data:`IMPORTED_HISTORY_KEY`. +#: messages carry :data:`IMPORTED_HISTORY_KEY`. Memory capture reads the +#: thread state's :data:`IMPORTED_HISTORY_CHANNEL`, which branches and +#: compaction carry; this metadata only finds copies to migrate. SHARE_IMPORT_COMPLETE_KEY = "share_import_complete" SHARE_IMPORT_HISTORY_MARKED_KEY = "share_import_history_marked" @@ -142,7 +146,7 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, for artifact in artifacts: await run_file_io(publish_snapshot, sandbox, artifact["path"], artifact["content"], area="outputs", max_bytes=MAX_SHARE_FILE_BYTES) accessor, config = build_checkpoint_state_mutation_accessor(request, thread_id=thread_id, as_node="branch") - await accessor.aupdate(config, {"messages": Overwrite(messages), "title": title, "artifacts": Overwrite([OUTPUT_PREFIX + a["path"] for a in artifacts])}, as_node="branch") + await accessor.aupdate(config, {"messages": Overwrite(messages), "title": title, "artifacts": Overwrite([OUTPUT_PREFIX + a["path"] for a in artifacts]), IMPORTED_HISTORY_CHANNEL: "share"}, as_node="branch") events = build_branch_history_seed_events(messages, thread_id=thread_id, run_id_prefix=f"branch-seed-{thread_id}", parent_thread_id=thread_id) await write_history_seed(request, events, reservation=reservation, seed_kind="branch", thread=record) await threads.update_metadata(thread_id, {SHARE_IMPORT_COMPLETE_KEY: True, SHARE_IMPORT_HISTORY_MARKED_KEY: True}, user_id=owner) @@ -161,59 +165,162 @@ async def fork_share(request: Request, repo: ThreadShareRepository, token: str, async def _imported_message_ids(request: Request, accessor, config: dict) -> set[str] | None: """IDs of the history the import wrote as the thread's root checkpoint. - ``None`` when the root is gone or unreadable: guessing from a later - checkpoint would mark the owner's own turns as someone else's. + ``None`` when the root is gone or unreadable, including a failed read: + guessing from a later checkpoint would mark the owner's own turns as + someone else's. """ - tuples = [item async for item in get_checkpointer(request).alist(config)] - if not tuples or tuples[-1].parent_config is not None: + try: + tuples = [item async for item in get_checkpointer(request).alist(config)] + if not tuples or tuples[-1].parent_config is not None: + return None + root_id = tuples[-1].config["configurable"]["checkpoint_id"] + snapshot = await accessor.aget({**config, "configurable": {**config["configurable"], "checkpoint_id": root_id}}) + except Exception: + logger.warning("Could not read the import checkpoint of thread %s", sanitize_log_param(config["configurable"].get("thread_id")), exc_info=True) return None - root_id = tuples[-1].config["configurable"]["checkpoint_id"] - snapshot = await accessor.aget({**config, "configurable": {**config["configurable"], "checkpoint_id": root_id}}) messages = snapshot.values.get("messages") if isinstance(snapshot.values, dict) else None ids = {message.id for message in messages or () if getattr(message, "id", None)} return ids or None -async def ensure_share_import_history_marked(request: Request, thread_id: str, *, threads: ThreadMetaStore | None, metadata_timeout: float) -> None: - """Mark the copied history of a share copy imported before marks existed. +def is_share_copy_metadata(metadata: object) -> bool: + """Return whether thread *metadata* records a completed share import.""" + return isinstance(metadata, Mapping) and metadata.get(SHARE_IMPORT_COMPLETE_KEY) is True - Migration shim, run before admission like ``ensure_checkpoint_history_seeded``: - without it, such a copy's history reaches memory extraction on the owner's - next run, also through the pre-compaction flush, which ignores extraction - watermarks. Remove it once those copies are no longer an upgrade source. - A busy or paused thread is left for a later run, because a checkpoint - write would race the active run or replace the pending interrupt. The - shim is best effort: a failure is logged and never blocks the run. + +def _share_provenance(values: object) -> object: + return values.get(IMPORTED_HISTORY_CHANNEL) if isinstance(values, Mapping) else None + + +def _has_share_provenance(values: object) -> bool: + """Whether the copied turns in *values* are resolved; an unresolved copy stays eligible for migration.""" + provenance = _share_provenance(values) + return bool(provenance) and provenance != IMPORTED_HISTORY_UNRESOLVED + + +def mark_imported(messages: list, imported: set[str]) -> list: + """Return *messages* with the import mark on those whose id is in *imported*.""" + + def mark(message): + if getattr(message, "id", None) not in imported or message.additional_kwargs.get(IMPORTED_HISTORY_KEY): + return message + return message.model_copy(update={"additional_kwargs": {**message.additional_kwargs, IMPORTED_HISTORY_KEY: "share"}}) + + return [mark(message) for message in messages] + + +async def _read_metadata(threads: ThreadMetaStore, thread_id: str, metadata_timeout: float) -> Mapping: + async with asyncio.timeout(metadata_timeout): + record = await threads.get(thread_id, user_id=None) + metadata = record.get("metadata") if isinstance(record, dict) else None + return metadata if isinstance(metadata, Mapping) else {} + + +async def _store_share_provenance(request: Request, thread_id: str, threads: ThreadMetaStore, accessor, config: dict, *, as_node: str = "branch") -> bool: + """Mark the copied history and set the state channel at the head. + + The caller holds a checkpoint-write reservation. Returns ``True`` once the + copied turns are marked. ``False`` means they are not: a busy or paused + head is left for later, because a write would race the active run or + replace the pending interrupt; a copy whose import checkpoint cannot be + read is recorded as unresolved, so memory capture skips it, and is tried + again on a later run. + """ + head = await accessor.aget(config) + if head.next or any(task.interrupts for task in head.tasks): + return False + # Keep the head's agent binding: without it, memory writes for the thread fail closed. + update_config = {**config, "metadata": checkpoint_agent_binding_metadata(getattr(head, "metadata", None))} + imported = await _imported_message_ids(request, accessor, config) + if imported is None: + logger.warning("Share copy %s has no readable import checkpoint; memory capture skips it until its copied history can be marked", sanitize_log_param(thread_id)) + if _share_provenance(head.values) != IMPORTED_HISTORY_UNRESOLVED: + await accessor.aupdate(update_config, {IMPORTED_HISTORY_CHANNEL: IMPORTED_HISTORY_UNRESOLVED}, as_node=as_node) + return False + messages = list(head.values.get("messages") or ()) + marked = [copy for copy, original in zip(mark_imported(messages, imported), messages, strict=True) if copy is not original] + await accessor.aupdate(update_config, {"messages": marked, IMPORTED_HISTORY_CHANNEL: "share"}, as_node=as_node) + await threads.update_metadata(thread_id, {SHARE_IMPORT_HISTORY_MARKED_KEY: True}, touch=False, user_id=None) + logger.info("Recorded share provenance for copy %s; marked %d copied messages", sanitize_log_param(thread_id), len(marked)) + return True + + +async def ensure_share_import_history_marked(request: Request, thread_id: str, *, threads: ThreadMetaStore | None, metadata_timeout: float) -> None: + """Record share provenance in a copy imported before it was stored in state. + + Migration shim, run before admission like ``ensure_checkpoint_history_seeded``. + Copies imported before #8422 lack the message marks, so their history + reaches memory extraction; copies imported before the state channel + existed lose their provenance once compaction removes the marked + messages. Remove the shim once those copies are no longer an upgrade + source. A busy or paused thread is left for a later run. Any other failure + is logged and retried on a later run, but memory capture reads the + provenance from state, so a copy whose state still has none is refused + with ``503`` instead of being remembered as an ordinary thread. """ if threads is None: return try: - async with asyncio.timeout(metadata_timeout): - record = await threads.get(thread_id, user_id=None) + metadata = await _read_metadata(threads, thread_id, metadata_timeout) except Exception: logger.warning("Could not read metadata of thread %s; its copied share history is checked on a later run", sanitize_log_param(thread_id), exc_info=True) return - metadata = record.get("metadata") if isinstance(record, dict) else None - if not isinstance(metadata, dict) or metadata.get(SHARE_IMPORT_COMPLETE_KEY) is not True or metadata.get(SHARE_IMPORT_HISTORY_MARKED_KEY) is True: + if not is_share_copy_metadata(metadata): return + accessor, config = build_checkpoint_state_mutation_accessor(request, thread_id=thread_id, as_node="branch") try: + if _has_share_provenance((await accessor.aget(config)).values): + return async with get_run_manager(request).reserve_thread_operation(thread_id, kind=ThreadOperationKind.checkpoint_write, user_id=get_trusted_internal_owner_user_id(request)): - accessor, config = build_checkpoint_state_mutation_accessor(request, thread_id=thread_id, as_node="branch") - head = await accessor.aget(config) - if head.next or any(task.interrupts for task in head.tasks): - return - imported = await _imported_message_ids(request, accessor, config) - if imported is None: - # Recorded as handled anyway, so later runs skip the history scan. - logger.warning("Share copy %s has no readable import checkpoint; its copied history stays unmarked", sanitize_log_param(thread_id)) - imported = set() - unmarked = [message for message in head.values.get("messages") or () if getattr(message, "id", None) in imported and not message.additional_kwargs.get(IMPORTED_HISTORY_KEY)] - if unmarked: - marked = [message.model_copy(update={"additional_kwargs": {**message.additional_kwargs, IMPORTED_HISTORY_KEY: "share"}}) for message in unmarked] - await accessor.aupdate(config, {"messages": marked}, as_node="branch") - await threads.update_metadata(thread_id, {SHARE_IMPORT_HISTORY_MARKED_KEY: True}, touch=False, user_id=None) - logger.info("Marked %d copied messages in share copy %s", len(unmarked), sanitize_log_param(thread_id)) + await _store_share_provenance(request, thread_id, threads, accessor, config) except ConflictError: logger.info("Share copy %s is busy; marking its copied history on a later run", sanitize_log_param(thread_id)) - except Exception: + except Exception as exc: logger.warning("Could not mark the copied history of share copy %s; retrying on a later run", sanitize_log_param(thread_id), exc_info=True) + if not await _state_records_provenance(accessor, config): + raise HTTPException(503, "The history of this copied conversation could not be checked; try again") from exc + + +async def _state_records_provenance(accessor, config: dict) -> bool: + """Whether the head carries any provenance, resolved or unresolved, for memory capture to read.""" + try: + return bool(_share_provenance((await accessor.aget(config)).values)) + except Exception: + return False + + +async def prepare_share_copy_compaction(request: Request, thread_id: str, accessor, config: dict, *, as_node: str, metadata_timeout: float) -> bool: + """Return whether a manual compaction may hand the removed messages to memory. + + Runs under the compaction's checkpoint-write reservation, so a copy that + has not been migrated is migrated here first: its unmarked copied turns + would otherwise be flushed as the owner's. When the thread's provenance + cannot be established, the compaction skips the memory flush. + """ + threads = getattr(request.app.state, "thread_store", None) + if threads is None: + # Sharing needs a thread store, so this thread is no copy. + return True + try: + metadata = await _read_metadata(threads, thread_id, metadata_timeout) + if not is_share_copy_metadata(metadata) or _has_share_provenance((await accessor.aget(config)).values): + return True + return await _store_share_provenance(request, thread_id, threads, accessor, config, as_node=as_node) + except Exception: + logger.warning("Could not establish the share provenance of thread %s; compacting without a memory flush", sanitize_log_param(thread_id), exc_info=True) + return False + + +async def branch_share_provenance(request: Request, source_metadata: object, source_values: object, source_accessor, source_config: dict) -> tuple[str, set[str]] | None: + """Channel value and copied-message IDs for a branch of a copy that has not been migrated. + + ``None`` means the branch inherits the source state unchanged: the source + is no copy, or its state already carries resolved provenance, which the + branch copies. Otherwise the branch gets the channel and these marks, so + it does not depend on the source's next run. A branch is never migrated + itself, so unreadable import history leaves it unresolved. + """ + if _has_share_provenance(source_values) or not is_share_copy_metadata(source_metadata): + return None + imported = await _imported_message_ids(request, source_accessor, source_config) + return (IMPORTED_HISTORY_UNRESOLVED, set()) if imported is None else ("share", imported) diff --git a/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/updater.py b/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/updater.py index 6e9641cced..4cbb7ae2cb 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/updater.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/updater.py @@ -862,6 +862,18 @@ def _memory_language_preference(messages: list[Any]) -> str: return "" +def _imported_history_note(messages: list[Any]) -> str: + # Set by the host on queued copies; DeerMem only reads the flag. + if any((getattr(message, "additional_kwargs", {}) or {}).get("deerflow_follows_imported_history") for message in messages): + return ( + "Note: this conversation continues a copy of another person's conversation, which is not shown here. " + "When the assistant repeats or summarizes details from that copy (a name, employer, role, health details, " + "preferences or standing instructions), they belong to the other person. Never record them as facts about " + "the user; record only what the user says about themselves." + ) + return "" + + class MemoryUpdater: """Updates memory using LLM based on conversation context.""" @@ -1428,12 +1440,12 @@ class MemoryUpdater: "consolidation_section": consolidation_section, } prompt = load_prompt_messages("memory_update", variables, agent_name=agent_name, prompts_dir=self._prompts_dir) - language_preference = _memory_language_preference(messages) - if language_preference: - # Per-run preference is data, not part of the cached system text. + # Per-run notes are data, not part of the cached system text. + notes = "\n\n".join(note for note in (_memory_language_preference(messages), _imported_history_note(messages)) if note) + if notes: for index, message in enumerate(prompt): if message.type == "human": - prompt[index] = message.model_copy(update={"content": f"{language_preference}\n\n{message.content}"}) + prompt[index] = message.model_copy(update={"content": f"{notes}\n\n{message.content}"}) break if config.prompt_prepend or config.prompt_append: # Extend trusted instructions only, after formatting the original diff --git a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py index 4726ea1f07..279fed80a0 100644 --- a/backend/packages/harness/deerflow/agents/memory/summarization_hook.py +++ b/backend/packages/harness/deerflow/agents/memory/summarization_hook.py @@ -9,7 +9,7 @@ from deerflow.agents.middlewares.summarization_middleware import SummarizationEv from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig from deerflow.runtime.user_context import resolve_runtime_user_id -from deerflow.utils.messages import without_imported_history +from deerflow.utils.messages import own_messages_for_memory def memory_flush_hook(event: SummarizationEvent, pii_redaction_config: PiiRedactionConfig | None = None) -> None: @@ -27,7 +27,7 @@ def memory_flush_hook(event: SummarizationEvent, pii_redaction_config: PiiRedact if not get_memory_config().enabled or not event.thread_id: return - messages = without_imported_history(list(event.messages_to_summarize)) + messages = own_messages_for_memory(list(event.messages_to_summarize), event.imported_history) if not messages: return user_id = resolve_runtime_user_id(event.runtime) diff --git a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py index 9e59634eba..b473aedc74 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py @@ -18,7 +18,7 @@ from deerflow.config.memory_config import get_memory_config from deerflow.config.pii_redaction_config import PiiRedactionConfig from deerflow.runtime.user_context import resolve_runtime_user_id from deerflow.trace_context import DEERFLOW_TRACE_METADATA_KEY, resolve_trace_id -from deerflow.utils.messages import ORIGINAL_USER_CONTENT_KEY, without_imported_history +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, ORIGINAL_USER_CONTENT_KEY, own_messages_for_memory if TYPE_CHECKING: from deerflow.config.memory_config import MemoryConfig @@ -210,7 +210,7 @@ class MemoryMiddleware(AgentMiddleware[MemoryMiddlewareState]): # History copied from another person's conversation is context, not # something this user said; leaving it out here covers every backend. - messages = without_imported_history(state.get("messages", [])) + messages = own_messages_for_memory(state.get("messages", []), state.get(IMPORTED_HISTORY_CHANNEL)) if not messages: logger.debug("No own messages in state, skipping memory update") return None diff --git a/backend/packages/harness/deerflow/agents/middlewares/summarization_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/summarization_middleware.py index 7ec08212cf..8e76e95f0f 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/summarization_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/summarization_middleware.py @@ -39,6 +39,7 @@ from deerflow.models.reasoning import resolve_reasoning_contract from deerflow.models.vllm_provider import VllmChatModel, count_tokens_with_replayed_reasoning from deerflow.runtime.events.catalog import MIDDLEWARE_SUMMARIZE_TAG from deerflow.utils.assembly_io import run_assembly +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL logger = logging.getLogger(__name__) _SUMMARY_TRIGGER_MESSAGE_NAME = "summary" @@ -132,6 +133,9 @@ class SummarizationEvent: thread_id: str | None agent_name: str | None runtime: Runtime + # The thread's ``imported_history`` state channel: the summarized messages + # may no longer carry their own import marks. + imported_history: str | None = None @dataclass(frozen=True) @@ -989,7 +993,7 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): # messages into durable memory for a summary that never materializes would # duplicate that work on the next attempt. Messages are still removed after # this returns (in _maybe_summarize), so hooks run before they are gone. - self._fire_hooks(messages_to_summarize, preserved_messages, runtime) + self._fire_hooks(messages_to_summarize, preserved_messages, runtime, imported_history=_imported_history(state)) self._record_compaction( source_content_hashes, summary=summary, @@ -1039,7 +1043,7 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): summary = str(summary) self._record_summary_telemetry(runtime, previous_summary, summary, len(messages_to_summarize), llm_call_skipped=llm_call_skipped) # Fire hooks only once a replacement summary exists (see compact_state). - await self._afire_hooks(messages_to_summarize, preserved_messages, runtime) + await self._afire_hooks(messages_to_summarize, preserved_messages, runtime, imported_history=_imported_history(state)) self._record_compaction( source_content_hashes, summary=summary, @@ -1126,6 +1130,8 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): messages_to_summarize: list[AnyMessage], preserved_messages: list[AnyMessage], runtime: Runtime, + *, + imported_history: str | None = None, ) -> None: if not self._before_summarization_hooks: return @@ -1136,6 +1142,7 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): thread_id=_resolve_thread_id(runtime), agent_name=_resolve_agent_name(runtime), runtime=runtime, + imported_history=imported_history, ) for hook in self._before_summarization_hooks: @@ -1150,6 +1157,8 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): messages_to_summarize: list[AnyMessage], preserved_messages: list[AnyMessage], runtime: Runtime, + *, + imported_history: str | None = None, ) -> None: """Async counterpart of :meth:`_fire_hooks`, run in a worker thread. @@ -1161,7 +1170,13 @@ class DeerFlowSummarizationMiddleware(SummarizationMiddleware): """ if not self._before_summarization_hooks: return - await asyncio.to_thread(self._fire_hooks, messages_to_summarize, preserved_messages, runtime) + await asyncio.to_thread(partial(self._fire_hooks, imported_history=imported_history), messages_to_summarize, preserved_messages, runtime) + + +def _imported_history(state: object) -> str | None: + # Persisted state is untrusted: only a string value names a source. + value = state.get(IMPORTED_HISTORY_CHANNEL) if isinstance(state, Mapping) else None + return value if isinstance(value, str) and value else None def _summary_model_thinking_enabled(name: str | None, app_config: Any) -> bool: diff --git a/backend/packages/harness/deerflow/agents/thread_state.py b/backend/packages/harness/deerflow/agents/thread_state.py index aecbb10b46..51eb45f298 100644 --- a/backend/packages/harness/deerflow/agents/thread_state.py +++ b/backend/packages/harness/deerflow/agents/thread_state.py @@ -481,6 +481,8 @@ class ThreadState(AgentState): task_history: NotRequired[dict | None] summary_text: NotRequired[str | None] background_tasks: NotRequired[list[BackgroundTaskState]] + # Server-owned: see ``deerflow.utils.messages.IMPORTED_HISTORY_CHANNEL``. + imported_history: NotRequired[str | None] def _normalize_messages(value: Any) -> list[AnyMessage]: diff --git a/backend/packages/harness/deerflow/runtime/context_compaction.py b/backend/packages/harness/deerflow/runtime/context_compaction.py index bccaffe7d2..02851ffbb0 100644 --- a/backend/packages/harness/deerflow/runtime/context_compaction.py +++ b/backend/packages/harness/deerflow/runtime/context_compaction.py @@ -18,6 +18,7 @@ from deerflow.runtime.checkpoint_state import CheckpointStateAccessor from deerflow.runtime.context_keys import CHECKPOINT_AGENT_NAME_METADATA_KEY, DEFAULT_AGENT_NAME_METADATA_VALUE from deerflow.runtime.goal import _call_checkpointer_method from deerflow.utils.assembly_io import run_assembly +from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL logger = logging.getLogger(__name__) _AGENT_CONFIG_NOT_LOADED = object() @@ -156,8 +157,13 @@ async def compact_thread_context( agent_name: str | None = None, model_name: str | None = None, app_config: AppConfig | None = None, + memory_flush: bool = True, ) -> ThreadCompactionResult: - """Summarize old messages in a thread and write a compacted checkpoint.""" + """Summarize old messages in a thread and write a compacted checkpoint. + + ``memory_flush=False`` compacts without handing the removed messages to + memory, for a caller that cannot tell which of them the user wrote. + """ # Off the event loop (see utils/AGENTS.md): reading the live config stats # and hashes config.yaml. The route passes no app_config. resolved_app_config = app_config or await run_assembly(get_app_config) @@ -216,7 +222,7 @@ async def compact_thread_context( app_config=resolved_app_config, keep=keep, run_model_name=run_model_name, - skip_memory_flush=not memory_enabled, + skip_memory_flush=not (memory_enabled and memory_flush), ) channel_values = snapshot.values or {} @@ -228,6 +234,7 @@ async def compact_thread_context( "messages": list(messages), "summary_text": channel_values.get("summary_text"), "task_history": channel_values.get("task_history"), + IMPORTED_HISTORY_CHANNEL: channel_values.get(IMPORTED_HISTORY_CHANNEL), } runtime_context = {"thread_id": thread_id, "user_id": user_id} diff --git a/backend/packages/harness/deerflow/utils/messages.py b/backend/packages/harness/deerflow/utils/messages.py index 4dbd195c36..f49d0818e4 100644 --- a/backend/packages/harness/deerflow/utils/messages.py +++ b/backend/packages/harness/deerflow/utils/messages.py @@ -25,6 +25,18 @@ UNTRUSTED_INPUT_KEY = "untrusted_input" #: would otherwise record the other person's statements as the importer's facts. IMPORTED_HISTORY_KEY = "deerflow_imported_history" +#: Server-owned thread-state channel set on a thread whose history was copied +#: from someone else's conversation; the value names the source (``"share"``). +#: It lives in state rather than thread metadata so that every checkpoint, a +#: compacted head and a branch carry it: compaction removes the copied messages +#: and their marks, and memory capture must still know the thread is a copy. +IMPORTED_HISTORY_CHANNEL = "imported_history" + +#: :data:`IMPORTED_HISTORY_CHANNEL` value for a copy whose copied turns could +#: not be told apart from the owner's: the history the import wrote is no longer +#: readable. Memory capture skips such a thread rather than guess. +IMPORTED_HISTORY_UNRESOLVED = "unresolved" + def without_imported_history(messages: list[Any]) -> list[Any]: """Drop messages carrying :data:`IMPORTED_HISTORY_KEY`; any truthy value counts.""" @@ -37,6 +49,29 @@ def without_imported_history(messages: list[Any]) -> list[Any]: return kept +#: Mark on queued memory copies, never on graph state: the conversation they +#: come from continues history copied from someone else. An assistant reply can +#: restate that person's details, so extraction must not read them as the user's. +FOLLOWS_IMPORTED_HISTORY_KEY = "deerflow_follows_imported_history" + + +def own_messages_for_memory(messages: list[Any], imported_history: object = None) -> list[Any]: + """Drop imported history and mark the remaining copies when the thread is a copy. + + *imported_history* is the thread's :data:`IMPORTED_HISTORY_CHANNEL` value. + The thread also counts as a copy when a message carries the import mark, + which covers state written before the channel existed. Nothing is + returned for :data:`IMPORTED_HISTORY_UNRESOLVED`. + """ + if imported_history == IMPORTED_HISTORY_UNRESOLVED: + return [] + own = without_imported_history(messages) + is_copy = len(own) != len(messages) or bool(imported_history) + if not is_copy: + return own + return [message.model_copy(update={"additional_kwargs": {**message.additional_kwargs, FOLLOWS_IMPORTED_HISTORY_KEY: True}}) for message in own] + + #: Suffix ``DynamicContextMiddleware``'s ID-swap gives the real user message; the #: reminder SystemMessage takes the original id so ``add_messages`` can replace it #: in place. It lives here rather than beside the middleware because the message diff --git a/backend/tests/test_gateway_services.py b/backend/tests/test_gateway_services.py index c0144e520b..1a1f3b9cb7 100644 --- a/backend/tests/test_gateway_services.py +++ b/backend/tests/test_gateway_services.py @@ -260,6 +260,23 @@ def test_external_loop_cap_is_rejected(boundary): assert error.value.detail == "External loop_cap state is not allowed" +@pytest.mark.parametrize("boundary", ["run", "state"]) +@pytest.mark.parametrize("value", ["share", None]) +def test_external_imported_history_channel_is_rejected(boundary, value): + """Only share import sets it; a caller could otherwise clear a copy's provenance or forge it.""" + from fastapi import HTTPException + + from app.gateway.services import normalize_input, strip_server_owned_state_metadata + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL + + transform = normalize_input if boundary == "run" else strip_server_owned_state_metadata + with pytest.raises(HTTPException) as error: + transform({IMPORTED_HISTORY_CHANNEL: value}) + + assert error.value.status_code == 400 + assert error.value.detail == "External imported_history state is not allowed" + + @pytest.mark.parametrize("mode", ["full", "delta"]) def test_external_run_goal_clears_the_previous_goal_outcome(mode): """A caller goal replaces the goal, so the record of the earlier met goal must go.""" diff --git a/backend/tests/test_memory_middleware.py b/backend/tests/test_memory_middleware.py index 17e376ed74..6b4b4d9431 100644 --- a/backend/tests/test_memory_middleware.py +++ b/backend/tests/test_memory_middleware.py @@ -6,7 +6,7 @@ from langgraph.runtime import Runtime from deerflow.agents.middlewares import memory_middleware as memory_middleware_module from deerflow.agents.middlewares.memory_middleware import MemoryMiddleware from deerflow.config.memory_config import MemoryConfig -from deerflow.utils.messages import IMPORTED_HISTORY_KEY +from deerflow.utils.messages import FOLLOWS_IMPORTED_HISTORY_KEY, IMPORTED_HISTORY_KEY _IMPORTED = {IMPORTED_HISTORY_KEY: "share"} @@ -26,8 +26,14 @@ def test_after_agent_skips_history_imported_from_another_conversation(monkeypatc middleware = MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) runtime = Runtime(context={"thread_id": "copy", "user_id": "importer"}) - middleware.after_agent({"messages": _imported_then_own()}, runtime) - assert [message.id for message in manager.add.call_args.args[1]] == ["own-h", "own-a"] + state_messages = _imported_then_own() + middleware.after_agent({"messages": state_messages}, runtime) + queued = manager.add.call_args.args[1] + assert [message.id for message in queued] == ["own-h", "own-a"] + # Extraction learns that the conversation continues someone else's; the + # thread state does not change. + assert all(message.additional_kwargs[FOLLOWS_IMPORTED_HISTORY_KEY] is True for message in queued) + assert not any(FOLLOWS_IMPORTED_HISTORY_KEY in message.additional_kwargs for message in state_messages) manager.reset_mock() middleware.after_agent({"messages": _imported_then_own()[:2]}, runtime) @@ -48,13 +54,98 @@ def test_compaction_flush_skips_history_imported_from_another_conversation(monke hook_module.memory_flush_hook(event) flush(_imported_then_own()) - assert [message.id for message in manager.add_nowait.call_args.args[1]] == ["own-h", "own-a"] + queued = manager.add_nowait.call_args.args[1] + assert [message.id for message in queued] == ["own-h", "own-a"] + assert all(message.additional_kwargs[FOLLOWS_IMPORTED_HISTORY_KEY] is True for message in queued) manager.reset_mock() flush(_imported_then_own()[:2]) manager.add_nowait.assert_not_called() +def test_own_conversation_is_queued_without_the_imported_history_mark(monkeypatch): + manager = MagicMock() + monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) + middleware = MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) + + middleware.after_agent({"messages": _imported_then_own()[2:]}, Runtime(context={"thread_id": "own", "user_id": "u"})) + + assert not any(FOLLOWS_IMPORTED_HISTORY_KEY in message.additional_kwargs for message in manager.add.call_args.args[1]) + + +def test_share_copy_channel_marks_capture_after_compaction(monkeypatch): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL + + manager = MagicMock() + monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) + middleware = MemoryMiddleware(memory_config=MemoryConfig(enabled=True)) + + # Compaction removed the copied turns; only the state channel says this is a copy. + state = {"messages": _imported_then_own()[2:], IMPORTED_HISTORY_CHANNEL: "share"} + middleware.after_agent(state, Runtime(context={"thread_id": "copy", "user_id": "u"})) + + assert all(message.additional_kwargs[FOLLOWS_IMPORTED_HISTORY_KEY] is True for message in manager.add.call_args.args[1]) + + +def test_compaction_flush_marks_capture_from_the_share_copy_channel(monkeypatch): + import deerflow.agents.memory.summarization_hook as hook_module + from deerflow.agents.middlewares.summarization_middleware import SummarizationEvent + + manager = MagicMock() + monkeypatch.setattr(hook_module, "get_memory_config", lambda: MemoryConfig(enabled=True)) + monkeypatch.setattr(hook_module, "get_memory_manager", lambda: manager) + monkeypatch.setattr(hook_module, "resolve_runtime_user_id", lambda runtime: "importer") + + # The batch holds only the visitor's turns; only the event's channel value says this is a copy. + runtime = Runtime(context={"thread_id": "copy"}) + event = SummarizationEvent(messages_to_summarize=tuple(_imported_then_own()[2:]), preserved_messages=(), thread_id="copy", agent_name=None, runtime=runtime, imported_history="share") + hook_module.memory_flush_hook(event) + + assert all(message.additional_kwargs[FOLLOWS_IMPORTED_HISTORY_KEY] is True for message in manager.add_nowait.call_args.args[1]) + + +def test_unresolved_share_copy_is_not_captured(monkeypatch): + import deerflow.agents.memory.summarization_hook as hook_module + from deerflow.agents.middlewares.summarization_middleware import SummarizationEvent + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_UNRESOLVED + + manager = MagicMock() + monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) + monkeypatch.setattr(hook_module, "get_memory_config", lambda: MemoryConfig(enabled=True)) + monkeypatch.setattr(hook_module, "get_memory_manager", lambda: manager) + monkeypatch.setattr(hook_module, "resolve_runtime_user_id", lambda runtime: "importer") + # Unmarked copied turns cannot be told from the owner's, so neither path queues anything. + unmarked = [HumanMessage(content="I am the sharer", id="h"), AIMessage(content="Hello, sharer", id="a")] + + MemoryMiddleware(memory_config=MemoryConfig(enabled=True)).after_agent({"messages": unmarked, IMPORTED_HISTORY_CHANNEL: IMPORTED_HISTORY_UNRESOLVED}, Runtime(context={"thread_id": "copy", "user_id": "u"})) + hook_module.memory_flush_hook( + SummarizationEvent(messages_to_summarize=tuple(unmarked), preserved_messages=(), thread_id="copy", agent_name=None, runtime=Runtime(context={"thread_id": "copy"}), imported_history=IMPORTED_HISTORY_UNRESOLVED) + ) + + manager.add.assert_not_called() + manager.add_nowait.assert_not_called() + + +def test_deermem_prompt_warns_that_restated_copied_details_are_not_the_users(): + from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig + from deerflow.agents.memory.backends.deermem.deermem.core.storage import create_empty_memory + from deerflow.agents.memory.backends.deermem.deermem.core.updater import MemoryUpdater + + storage = MagicMock() + storage.load.return_value = create_empty_memory() + updater = MemoryUpdater(DeerMemConfig(), storage) + own = [HumanMessage(content="Summarize this conversation", id="h"), AIMessage(content="Lin, CFO at Contoso, asked for French.", id="a")] + marked = [message.model_copy(update={"additional_kwargs": {FOLLOWS_IMPORTED_HISTORY_KEY: True}}) for message in own] + + _, plain_prompt = updater._prepare_update_prompt(own, None, frozenset()) + _, marked_prompt = updater._prepare_update_prompt(marked, None, frozenset()) + + assert "another person's conversation" not in plain_prompt[1].content + assert "another person's conversation" in marked_prompt[1].content + # The note is per-conversation data, so the cached system text stays the same. + assert marked_prompt[0].content == plain_prompt[0].content + + def test_after_agent_queues_memory_under_runtime_user(monkeypatch): manager = MagicMock() monkeypatch.setattr(memory_middleware_module, "get_memory_manager", lambda: manager) diff --git a/backend/tests/test_shares_router.py b/backend/tests/test_shares_router.py index db521c183d..01d5c29e73 100644 --- a/backend/tests/test_shares_router.py +++ b/backend/tests/test_shares_router.py @@ -226,15 +226,17 @@ async def test_fork_history_is_not_captured_into_recipient_memory(share_app, mon from deerflow.agents.middlewares import memory_middleware from deerflow.config.memory_config import MemoryConfig - from deerflow.utils.messages import IMPORTED_HISTORY_KEY + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY ctx = share_app share = await make_share(ctx) response = await ctx.client.post(f"/api/shares/{share['token']}/fork", json={"request_id": str(uuid4())}, headers=headers("bob")) assert response.status_code == 200, response.text accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=response.json()["thread_id"], as_node="branch") - copied = (await accessor.aget(config)).values["messages"] + head = await accessor.aget(config) + copied = head.values["messages"] assert copied and all(message.additional_kwargs.get(IMPORTED_HISTORY_KEY) == "share" for message in copied) + assert head.values[IMPORTED_HISTORY_CHANNEL] == "share" # The recipient's first turn in the copy is the first memory capture for this thread. own = [HumanMessage(content="Bob's own question", id="bob-q"), AIMessage(content="Bob's answer", id="bob-a")] manager = MagicMock() @@ -259,7 +261,7 @@ async def _copy_from_an_earlier_build(ctx): async def test_copy_from_an_earlier_build_is_marked_once_the_thread_is_free(share_app): - from deerflow.utils.messages import IMPORTED_HISTORY_KEY + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY ctx = share_app threads = ctx.app.state.thread_store @@ -276,6 +278,7 @@ async def test_copy_from_an_earlier_build_is_marked_once_the_thread_is_free(shar marked = await accessor.aget(config) # Only the turns the import wrote are someone else's; Bob's turn stays his. assert marks(marked) == {"copied-h": "share", "copied-a": "share", "bob-q": None, "bob-a": None} + assert marked.values[IMPORTED_HISTORY_CHANNEL] == "share" assert (await threads.get(thread_id, user_id=None))["metadata"][share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY] is True await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) assert (await accessor.aget(config)).config == marked.config @@ -312,7 +315,8 @@ async def test_copy_from_an_earlier_build_keeps_a_pending_interrupt(share_app, m assert share_fork.SHARE_IMPORT_HISTORY_MARKED_KEY not in (await ctx.app.state.thread_store.get(thread_id, user_id=None))["metadata"] -async def test_next_run_in_a_copy_from_an_earlier_build_captures_only_the_owners_turns(share_app, monkeypatch, tmp_path): +def _wire_gateway_runs(ctx, monkeypatch, tmp_path): + """Serve real runs through the Gateway; returns the mocked memory manager.""" from unittest.mock import AsyncMock, MagicMock from _agent_e2e_helpers import FakeToolCallingModel @@ -324,10 +328,8 @@ async def test_next_run_in_a_copy_from_an_earlier_build_captures_only_the_owners from deerflow.persistence.projects import ProjectRepository from deerflow.runtime.stream_bridge.memory import MemoryStreamBridge - ctx = share_app if not isinstance(ctx.app.state.run_event_store, DbRunEventStore) or ctx.app.state.checkpoint_channel_mode != "full": pytest.skip("exercises the gateway runtime with durable full checkpoints") - thread_id, _, _ = await _copy_from_an_earlier_build(ctx) monkeypatch.setenv("DEER_FLOW_HOME", str(ctx.paths.base_dir)) monkeypatch.setattr("deerflow.config.paths._paths", ctx.paths) config = app_config.AppConfig.model_validate( @@ -348,14 +350,286 @@ async def test_next_run_in_a_copy_from_an_earlier_build_captures_only_the_owners monkeypatch.setattr(agent, "create_chat_model", lambda **kwargs: FakeToolCallingModel(responses=[AIMessage(content="Use lst[::-1].")])) manager = MagicMock(aadd=AsyncMock()) monkeypatch.setattr(memory_middleware, "get_memory_manager", lambda: manager) + return manager + +async def _run_and_capture(ctx, manager, thread_id): result = await ctx.client.post(f"/api/threads/{thread_id}/runs/wait", json={"input": {"messages": [{"type": "human", "content": "How do I reverse a list?"}]}}, headers=headers("bob")) assert result.status_code == 200, result.text - captured = manager.aadd.call_args.args[1] + return manager.aadd.call_args.args[1] + + +def _wire_manual_compaction(monkeypatch): + """Enable compaction with a fake summary model; returns the mocked flush manager.""" + from unittest.mock import MagicMock + + from langchain_core.language_models.fake_chat_models import FakeListChatModel + + from deerflow.agents.memory import summarization_hook + from deerflow.agents.middlewares import summarization_middleware + from deerflow.config import app_config + + current = app_config._app_config + monkeypatch.setattr(app_config, "_app_config", current.model_copy(update={"summarization": current.summarization.model_copy(update={"enabled": True})})) + monkeypatch.setattr(summarization_middleware, "create_chat_model", lambda **kwargs: FakeListChatModel(responses=["SUMMARY"])) + flush = MagicMock() + monkeypatch.setattr(summarization_hook, "get_memory_manager", lambda: flush) + monkeypatch.setattr(summarization_hook, "get_memory_config", lambda: SimpleNamespace(enabled=True)) + return flush + + +async def _compact(ctx, thread_id): + response = await ctx.client.post(f"/api/threads/{thread_id}/compact", json={"force": True, "keep": {"type": "messages", "value": 1}}, headers=headers("bob")) + assert response.status_code == 200 and response.json()["compacted"] is True, response.text + + +async def _bind_to_default_agent(accessor, config): + """Bob already chatted in the copy on the earlier build, which bound its checkpoints to an agent.""" + from deerflow.runtime.context_keys import CHECKPOINT_AGENT_NAME_METADATA_KEY, DEFAULT_AGENT_NAME_METADATA_VALUE + + bound = {**config, "metadata": {CHECKPOINT_AGENT_NAME_METADATA_KEY: DEFAULT_AGENT_NAME_METADATA_VALUE}} + await accessor.aupdate(bound, {"messages": [HumanMessage(content="Bob again", id="bob-q2"), AIMessage(content="Noted", id="bob-a2")]}, as_node="branch") + + +def _follows_copy(messages): + from deerflow.utils.messages import FOLLOWS_IMPORTED_HISTORY_KEY + + return bool(messages) and all(message.additional_kwargs.get(FOLLOWS_IMPORTED_HISTORY_KEY) is True for message in messages) + + +async def test_next_run_in_a_copy_from_an_earlier_build_captures_only_the_owners_turns(share_app, monkeypatch, tmp_path): + ctx = share_app + manager = _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, _, _ = await _copy_from_an_earlier_build(ctx) + + captured = await _run_and_capture(ctx, manager, thread_id) assert [message.content for message in captured if message.type in {"human", "ai"}][:2] == ["Bob's own question", "Bob's answer"] assert not any("Alice" in str(message.content) for message in captured) +async def test_copy_keeps_its_provenance_through_compaction_branching_and_continuing(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_KEY + + ctx = share_app + manager = _wire_gateway_runs(ctx, monkeypatch, tmp_path) + share = await make_share(ctx) + response = await ctx.client.post(f"/api/shares/{share['token']}/fork", json={"request_id": str(uuid4())}, headers=headers("bob")) + assert response.status_code == 200, response.text + copy_id = response.json()["thread_id"] + # Two own turns: compaction keeps the latest one and flushes the first. + await _run_and_capture(ctx, manager, copy_id) + await _run_and_capture(ctx, manager, copy_id) + flush = _wire_manual_compaction(monkeypatch) + + # Compaction removes every copied message, and their marks with them. + await _compact(ctx, copy_id) + flushed = flush.add_nowait.call_args.args[1] + assert _follows_copy(flushed) and not any(message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in flushed) + accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=copy_id, as_node="branch") + head = (await accessor.aget(config)).values["messages"] + assert not any(message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in head) + + # A second compaction flushes a batch with no marked message left in it. + await _run_and_capture(ctx, manager, copy_id) + await _compact(ctx, copy_id) + assert _follows_copy(flush.add_nowait.call_args.args[1]) + head = (await accessor.aget(config)).values["messages"] + + # A branch of the compacted copy and a run in it still capture as a copy. + branched = await ctx.client.post(f"/api/threads/{copy_id}/branches", json={"message_id": head[-1].id}, headers=headers("bob")) + assert branched.status_code == 200, branched.text + assert _follows_copy(await _run_and_capture(ctx, manager, branched.json()["thread_id"])) + assert _follows_copy(await _run_and_capture(ctx, manager, copy_id)) + + +async def test_manual_compaction_of_an_unmigrated_copy_flushes_only_the_owners_turns(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL + + ctx = share_app + _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + await _bind_to_default_agent(accessor, config) + flush = _wire_manual_compaction(monkeypatch) + + # No run since the upgrade, so the copied turns are still unmarked. + await _compact(ctx, thread_id) + + flushed = flush.add_nowait.call_args.args[1] + # Compaction keeps the latest request, so Bob's earlier turn is what it flushes. + assert [message.id for message in flushed] == ["bob-q", "bob-a"] and _follows_copy(flushed) + assert (await accessor.aget(config)).values[IMPORTED_HISTORY_CHANNEL] == "share" + + +async def test_manual_compaction_skips_the_memory_flush_when_share_provenance_is_unknown(share_app, monkeypatch, tmp_path): + ctx = share_app + _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + await _bind_to_default_agent(accessor, config) + flush = _wire_manual_compaction(monkeypatch) + + async def metadata_unavailable(*args, **kwargs): + raise TimeoutError("metadata read timed out") + + monkeypatch.setattr(share_fork, "_read_metadata", metadata_unavailable) + + await _compact(ctx, thread_id) + + flush.add_nowait.assert_not_called() + + +async def test_copy_whose_import_history_is_unreadable_is_kept_out_of_memory_until_resolved(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_UNRESOLVED + + ctx = share_app + manager = _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + await _bind_to_default_agent(accessor, config) + flush = _wire_manual_compaction(monkeypatch) + readable = share_fork._imported_message_ids + + async def import_checkpoint_unavailable(*args, **kwargs): + return None + + # The metadata says legacy copy, but which turns were copied cannot be read. + monkeypatch.setattr(share_fork, "_imported_message_ids", import_checkpoint_unavailable) + await _compact(ctx, thread_id) + flush.add_nowait.assert_not_called() + assert (await accessor.aget(config)).values[IMPORTED_HISTORY_CHANNEL] == IMPORTED_HISTORY_UNRESOLVED + result = await ctx.client.post(f"/api/threads/{thread_id}/runs/wait", json={"input": {"messages": [{"type": "human", "content": "And sets?"}]}}, headers=headers("bob")) + assert result.status_code == 200, result.text + manager.aadd.assert_not_called() + + # Once the import history can be read, the next run resolves it. + monkeypatch.setattr(share_fork, "_imported_message_ids", readable) + captured = await _run_and_capture(ctx, manager, thread_id) + assert (await accessor.aget(config)).values[IMPORTED_HISTORY_CHANNEL] == "share" + assert _follows_copy(captured) and not any("Alice" in str(message.content) for message in captured) + # The turn Bob wrote while the copy was unresolved is not lost. + assert "And sets?" in [message.content for message in captured] + + +def _fail_import_history_reads(ctx, monkeypatch): + """Make reading a thread's checkpoint history raise, as an unavailable checkpoint store does.""" + checkpointer = ctx.app.state.checkpointer + + class Failing: + def alist(self, *args, **kwargs): + raise ConnectionError("checkpoint store unavailable") + + def __getattr__(self, name): + return getattr(checkpointer, name) + + monkeypatch.setattr(share_fork, "get_checkpointer", lambda request: Failing()) + + +async def test_copy_whose_import_history_read_fails_is_kept_out_of_memory(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_UNRESOLVED + + ctx = share_app + manager = _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + + _fail_import_history_reads(ctx, monkeypatch) + result = await ctx.client.post(f"/api/threads/{thread_id}/runs/wait", json={"input": {"messages": [{"type": "human", "content": "And sets?"}]}}, headers=headers("bob")) + + assert result.status_code == 200, result.text + assert (await accessor.aget(config)).values[IMPORTED_HISTORY_CHANNEL] == IMPORTED_HISTORY_UNRESOLVED + manager.aadd.assert_not_called() + + +async def test_run_in_a_copy_is_refused_while_its_provenance_cannot_be_recorded(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL + + ctx = share_app + manager = _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + build = share_fork.build_checkpoint_state_mutation_accessor + + class ReadOnly: + """The real accessor, failing every state write.""" + + def __init__(self, inner): + self.inner = inner + + async def aupdate(self, *args, **kwargs): + raise ConnectionError("checkpoint store unavailable") + + def __getattr__(self, name): + return getattr(self.inner, name) + + def read_only_accessor(*args, **kwargs): + inner, read_only_config = build(*args, **kwargs) + return ReadOnly(inner), read_only_config + + monkeypatch.setattr(share_fork, "build_checkpoint_state_mutation_accessor", read_only_accessor) + result = await ctx.client.post(f"/api/threads/{thread_id}/runs/wait", json={"input": {"messages": [{"type": "human", "content": "And sets?"}]}}, headers=headers("bob")) + + assert result.status_code == 503, result.text + manager.aadd.assert_not_called() + assert IMPORTED_HISTORY_CHANNEL not in (await accessor.aget(config)).values + + # Once provenance can be recorded, the run is admitted again. + monkeypatch.setattr(share_fork, "build_checkpoint_state_mutation_accessor", build) + captured = await _run_and_capture(ctx, manager, thread_id) + assert _follows_copy(captured) and not any("Alice" in str(message.content) for message in captured) + + +@pytest.mark.parametrize("failure", ["missing", "read_error"]) +async def test_branch_of_a_copy_with_unreadable_import_history_is_unresolved(share_app, monkeypatch, tmp_path, failure): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_UNRESOLVED + + ctx = share_app + _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, _, _ = await _copy_from_an_earlier_build(ctx) + + async def import_checkpoint_unavailable(*args, **kwargs): + return None + + if failure == "missing": + monkeypatch.setattr(share_fork, "_imported_message_ids", import_checkpoint_unavailable) + else: + _fail_import_history_reads(ctx, monkeypatch) + branched = await ctx.client.post(f"/api/threads/{thread_id}/branches", json={"message_id": "bob-a"}, headers=headers("bob")) + + assert branched.status_code == 200, branched.text + accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=branched.json()["thread_id"], as_node="branch") + assert (await accessor.aget(config)).values[IMPORTED_HISTORY_CHANNEL] == IMPORTED_HISTORY_UNRESOLVED + + +async def test_branch_of_an_unmigrated_copy_marks_the_copied_turns(share_app, monkeypatch, tmp_path): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY + + ctx = share_app + _wire_gateway_runs(ctx, monkeypatch, tmp_path) + thread_id, _, _ = await _copy_from_an_earlier_build(ctx) + + branched = await ctx.client.post(f"/api/threads/{thread_id}/branches", json={"message_id": "bob-a"}, headers=headers("bob")) + + assert branched.status_code == 200, branched.text + accessor, config = build_checkpoint_state_mutation_accessor(ctx.request, thread_id=branched.json()["thread_id"], as_node="branch") + head = await accessor.aget(config) + assert {message.id: message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in head.values["messages"]} == {"copied-h": "share", "copied-a": "share", "bob-q": None, "bob-a": None} + assert head.values[IMPORTED_HISTORY_CHANNEL] == "share" + + +async def test_copy_from_the_marking_build_gains_the_state_channel(share_app): + from deerflow.utils.messages import IMPORTED_HISTORY_CHANNEL, IMPORTED_HISTORY_KEY + + ctx = share_app + threads = ctx.app.state.thread_store + thread_id, accessor, config = await _copy_from_an_earlier_build(ctx) + # As #8422 imported it: messages already marked, no state channel yet. + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) + head = await accessor.aget(config) + await accessor.aupdate(config, {IMPORTED_HISTORY_CHANNEL: None}, as_node="branch") + + await share_fork.ensure_share_import_history_marked(ctx.request, thread_id, threads=threads, metadata_timeout=5) + + migrated = await accessor.aget(config) + assert migrated.values[IMPORTED_HISTORY_CHANNEL] == "share" + assert [message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in migrated.values["messages"]] == [message.additional_kwargs.get(IMPORTED_HISTORY_KEY) for message in head.values["messages"]] + + async def test_share_import_metadata_is_server_owned(share_app): ctx = share_app thread_id = str(uuid4()) diff --git a/backend/tests/test_summarization_middleware.py b/backend/tests/test_summarization_middleware.py index 8d8e960d04..de6cade4f4 100644 --- a/backend/tests/test_summarization_middleware.py +++ b/backend/tests/test_summarization_middleware.py @@ -116,6 +116,27 @@ def test_before_summarization_hook_receives_messages_before_compression() -> Non assert [message.content for message in result["messages"][1:]] == ["user-2", "assistant-2"] +def test_before_summarization_hook_receives_the_imported_history_channel() -> None: + """Compaction removes the copied messages and their marks; the hook still learns the thread is a copy.""" + captured: list[SummarizationEvent] = [] + middleware = _middleware(before_summarization=[captured.append]) + + middleware.before_model({"messages": _messages(), "imported_history": "share"}, _runtime()) + middleware.before_model({"messages": _messages()}, _runtime()) + + assert [event.imported_history for event in captured] == ["share", None] + + +@pytest.mark.anyio +async def test_abefore_summarization_hook_receives_the_imported_history_channel() -> None: + captured: list[SummarizationEvent] = [] + middleware = _middleware(before_summarization=[captured.append]) + + await middleware.abefore_model({"messages": _messages(), "imported_history": "share"}, _runtime()) + + assert [event.imported_history for event in captured] == ["share"] + + def test_compaction_preserves_all_state_system_messages_in_order() -> None: """State-level instructions, including legacy untagged reminders, stay authoritative.""" captured: list[SummarizationEvent] = [] diff --git a/docs/guide/sharing.md b/docs/guide/sharing.md index d3e7fe0467..e34270f3ce 100644 --- a/docs/guide/sharing.md +++ b/docs/guide/sharing.md @@ -35,9 +35,25 @@ usable after the source link is revoked. The copied messages are context for the model, not something the visitor said, so memory extraction skips them, also when compaction removes them. New turns in -the copy are remembered as in any other conversation, including assistant replies -that repeat copied content. A copy made before this behavior existed has its -copied messages marked before its next run. +the copy are remembered as in any other conversation. With the default DeerMem +backend, extraction is also told that the conversation continues someone else's, +so details an assistant reply repeats from the copy, such as the sharer's name or +preferences, are not recorded as the visitor's. Other memory backends receive the +visitor's turns without that note. + +The copy records its origin in server-owned thread state, so compaction, a branch +of the copy and later runs keep it. A copy made before this behavior existed is +updated before its next run, before a manual compaction and when it is branched. +If a manual compaction cannot determine whether the thread is such a copy, it +compacts without updating memory. When the history the import wrote can no +longer be read, the copy's own turns cannot be told from the copied ones, so +memory is not updated from that conversation until a later run can read it. When +the update cannot be stored at all, for example while the checkpoint store is +unavailable, the run is refused with `503` and can be retried. Two +cases can still pass the copied turns of such an older copy to memory: a run that +starts from a checkpoint written before the update, for example an edit of an +earlier turn, and the run that resumes a tool approval that was pending when the +Gateway was upgraded. ## Deployment and limits