Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

feat: redact task content while keeping the task row and usage (#3783)

Zhenghao Yin078e5fcb0578
diff --git a/src/xagent/web/services/agent_service_manager.py b/src/xagent/web/services/agent_service_manager.py
index ddab48f9c..d432f4100 100644
--- a/src/xagent/web/services/agent_service_manager.py
+++ b/src/xagent/web/services/agent_service_manager.py
@@ -4003,13 +4003,17 @@ class AgentServiceManager:
expected_run_id: Optional[str] = None,
expected_run_generation: Optional[int] = None,
workspace_target: Optional[WorkspaceCleanupTarget] = None,
- ) -> None:
+ ) -> bool:
"""Clean a task runtime only for the run that scheduled cleanup.
``workspace_target`` is used only when no agent is cached: a cached one
knows its own workspace path and needs no capture. Deletion callers
pass a target captured before the task row was deleted, because the
path is no longer derivable once the row is gone.
+
+ Returns ``False`` when the run fence skipped the cleanup -- a later
+ acquisition owns the runtime, so neither it nor the workspace was
+ touched -- and ``True`` once the runtime was removed.
"""
current_run_id = self._agent_run_ids.get(task_id)
current_generation = self._agent_run_generations.get(task_id)
@@ -4030,7 +4034,7 @@ class AgentServiceManager:
expected_run_generation,
current_generation,
)
- return
+ return False
if expected_run_id is not None and (
(current_run_id is not None and current_run_id != expected_run_id)
or (build_lock is not None and build_lock.locked())
@@ -4041,7 +4045,7 @@ class AgentServiceManager:
expected_run_id,
current_run_id,
)
- return
+ return False
agent = self._agents.get(task_id)
cleanup_user_id = user_id
@@ -4094,6 +4098,7 @@ class AgentServiceManager:
if build_lock is not None and not build_lock.locked():
self._agent_build_locks.pop(task_id, None)
logger.info("Removed AgentService runtime for task %s", task_id)
+ return True
async def execute_task(
self,
diff --git a/src/xagent/web/services/task_content_redaction.py b/src/xagent/web/services/task_content_redaction.py
new file mode 100644
index 000000000..6c9cca0b7
--- /dev/null
+++ b/src/xagent/web/services/task_content_redaction.py
@@ -0,0 +1,373 @@
+"""Content redaction for tasks whose row must survive (conversation deletion).
+
+A host product lets its users delete their conversation history while the
+usage it bills from stays put. That usage is computed from ``tasks`` rows --
+the token counters and the rows themselves -- so deleting the task, the way
+``task_delete`` does, is not an option. Redaction removes everything a task
+*said or produced* and keeps what it *cost*; :func:`redact_task_rows` defines
+the exact split.
+
+Only settled tasks are redacted
+-------------------------------
+A task is redacted only when it is quiescent under the retention predicate:
+status COMPLETED or FAILED, no live execution lease, no command owed
+execution. Every other task is reported ``busy`` and left untouched. That
+includes tasks that will **not** settle on their own: a PAUSED task, one
+WAITING_FOR_USER, and a PENDING one with no command queued. Retrying those
+loops forever; the host must cancel or otherwise settle them first, then
+redact. Task deletion accepts those states because it removes the row and
+with it every reader; redaction keeps the row, and a parked run's resume
+state is exactly the content it removes.
+
+Per task, in order
+------------------
+1. One transaction locks the row, refuses a task that is not quiescent,
+ deletes the content rows and uploaded files, blanks the content columns,
+ and commits. The uploaded files' stored objects are deleted inside this
+ transaction, so the row lock is held across that object-storage I/O (see
+ ``task_deletion.delete_task_files`` for why); the task is quiescent, so
+ nothing else is waiting on it. A failure here rolls back that task's rows
+ and reports it ``failed``; the stored files it had already deleted stay
+ deleted, so a ``failed`` task is partially cleaned and must be re-run.
+2. After the commit, the read caches are invalidated, the ephemeral
+ connector values dropped, the cached agent runtime evicted and the
+ workspace directory removed -- unless a turn that started after the
+ commit already owns the runtime (see :func:`_release_task_runtime`).
+
+Eviction is process-local. ``remove_agent`` drops the agent this process
+has cached; a host running several agent worker processes must evict the
+task's cached agent on every other one itself, or a follow-up turn there
+can reuse the pre-redaction conversation the agent holds in memory and
+write it back. Task deletion has the same limit.
+
+The workspace goes after the commit because a directory cannot be restored
+by a rollback; it is found from the row, which still exists, so unlike task
+deletion nothing needs capturing up front and no cleanup obligation is
+recorded -- the obligation driver abandons any obligation whose task is live.
+A failed or skipped cleanup is reported per task in ``cleanup_failed``
+instead, and the caller re-runs the redaction for those: every step is
+idempotent, so a re-run finishes what an earlier one left.
+
+No ``content redacted`` column is added. Readers already treat every removed
+piece as a legitimate empty state (no transcript, no steps, no files, NULL
+output), ``traces_expired_at`` tells trace readers the steps were removed,
+and the host records the redaction on its own rows.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Callable, Literal, TypeVar, cast
+
+from sqlalchemy.orm import Session
+
+from ..models.task import Task
+from .agent_service_manager import get_agent_manager
+from .connector_runtime import drop_ephemeral_runtime_values_for_task
+from .hot_path_cache import invalidate_task_cache
+from .task_deletion import delete_task_files, redact_task_rows
+from .task_file_lifecycle import lock_attachment_task
+from .task_retention import retention_quiescent_condition
+from .task_workspace_cleanup import (
+ WorkspaceCleanupTarget,
+ capture_workspace_cleanup_target,
+)
+
+logger = logging.getLogger(__name__)
+
+_T = TypeVar("_T")
+
+
+@dataclass(frozen=True)
+class TaskContentRedactionReport:
+ """Which of the requested tasks ended in which state.
+
+ ``redacted`` includes tasks that were already redacted: the content is
+ gone either way. ``cleanup_failed`` tasks had their rows redacted and
+ committed, but removing the workspace or cached runtime raised, or was
+ skipped because a later turn already owns the runtime; re-run the
+ redaction for them once they settle; any other process's cached agent
+ is never evicted here (see the module docstring). ``failed`` tasks raised
+ in their row redaction and were rolled back, but the stored files deleted
+ before the failure stay deleted: they are partially cleaned, their file
+ rows may name missing bytes, and they must be re-run.
+ ``busy`` tasks are not settled and were left untouched -- see the module
+ docstring for the states the host must cancel first; ``missing`` ones do
+ not exist.
+ """
+
+ redacted: tuple[int, ...] = ()
+ cleanup_failed: tuple[int, ...] = ()
+ failed: tuple[int, ...] = ()
+ busy: tuple[int, ...] = ()
+ missing: tuple[int, ...] = ()
+
+
+@dataclass(frozen=True)
+class _RedactedRuntime:
+ """What the post-commit cleanup needs, read under the row lock.
+
+ ``run_id`` and ``run_generation`` identify the runtime that existed when
+ the rows were redacted, so the cleanup can tell it apart from one a later
+ turn acquires after the commit.
+ """
+
+ owner_id: int
+ run_id: str | None
+ run_generation: int | None
+
+
+def _run_on_quiescent_task(
+ db: Session,
+ task_id: int,
+ action: Callable[[Task], _T],
+ *,
+ now: datetime,
+) -> _T | Literal["busy", "missing"]:
+ """Run ``action`` on one locked, settled task in its own transaction.
+
+ Returns what ``action`` returned once its work is committed, ``"busy"``
+ when the task is not settled (nothing is changed; PAUSED,
+ WAITING_FOR_USER and a command-less PENDING task stay busy until the
+ host settles them), or ``"missing"``. The quiescence check reads the row
+ under the ``FOR UPDATE`` lock ``action`` runs under, so a command insert
+ (whose foreign key takes ``FOR KEY SHARE``) cannot slip in between on
+ PostgreSQL; ``FOR UPDATE`` is a no-op on SQLite, where the check and the
+ action are not atomic. Raises whatever ``action`` raises, after rolling
+ back.
+ """
+
+ committed = False
+ try:
+ task = lock_attachment_task(db, task_id, deleting=True)
+ if task is None:
+ return "missing"
+ # The caller's session may already hold this row from before the
+ # lock; the redaction rewrites ``agent_config`` from it and the
+ # eviction fence reads ``run_id``, so both must be the locked values.
+ db.refresh(task)
+ quiescent = (
+ db.query(Task.id)
+ .filter(Task.id == task_id, retention_quiescent_condition(now=now))
+ .first()
+ )
+ if quiescent is None:
+ return "busy"
+ result = action(task)
+ db.commit()
+ committed = True
+ return result
+ finally:
+ # Releases the row lock on every exit that did not commit.
+ if not committed:
+ db.rollback()
+
+
+def _redact_rows(db: Session, task: Task, *, now: datetime) -> _RedactedRuntime:
+ """Redact one locked task's rows; return what its cleanup needs."""
+ runtime = _RedactedRuntime(
+ owner_id=int(task.user_id),
+ run_id=cast(str | None, task.run_id),
+ run_generation=get_agent_manager().current_run_generation(int(task.id)),
+ )
+ redact_task_rows(db, task, now=now)
+ return runtime
+
+
+def _release_task_runtime(task_id: int, runtime: _RedactedRuntime) -> bool:
+ """Drop the in-memory state and the workspace of a redacted task.
+
+ ``remove_agent`` evicts this process's cached agent -- which still holds
+ the conversation in memory -- and removes the workspace through it, or
+ through the captured target when nothing is cached. It is fenced on the
+ run identity read under the lock: a turn that started after the commit
+ (or is building its runtime now) owns the runtime and workspace, and
+ ``remove_agent`` then leaves both alone rather than pull them out from
+ under it. That skip returns ``False``: the workspace still holds
+ pre-redaction files and nothing else removes them, so the caller must
+ re-run the redaction once that turn settles.
+
+ A scope that will not resolve raises rather than degrading to the
+ unscoped candidates: a redaction that cannot find the workspace must not
+ report success. The cached agent is evicted regardless, since it holds
+ the conversation in memory.
+
+ Process-local: another worker process's cached agent is the host's to
+ evict (see the module docstring).
+ """
+
+ # In-memory state first: a workspace failure below must not leave the
+ # caches serving the content the commit already removed.
+ drop_ephemeral_runtime_values_for_task(task_id)
+ invalidate_task_cache(task_id)
+ manager = get_agent_manager()
+
+ def evict(target: WorkspaceCleanupTarget | None) -> bool:
+ return manager.remove_agent(
+ task_id,
+ runtime.owner_id,
+ expected_run_id=runtime.run_id,
+ expected_run_generation=runtime.run_generation,
+ workspace_target=target,
+ )
+
+ try:
+ target = capture_workspace_cleanup_target(
+ task_id, runtime.owner_id, prefer_active_scope=False
+ )
+ except Exception:
+ # The cached agent still holds the conversation: evict it anyway. A
+ # cached agent removes its own workspace without a target; with none
+ # cached the eviction re-captures and fails the same way. Either way
+ # the task is reported ``cleanup_failed``.
+ evict(None)
+ raise
+ return evict(target)
+
+
+def redact_task_content(
+ db: Session, task_ids: Sequence[int]
+) -> TaskContentRedactionReport:
+ """Delete the content of each task while keeping its row and usage.
+
+ Owns its transactions: one per task, committed before that task's
+ workspace is removed, so a busy or failing task never holds back the
+ others and no row lock is held across the workspace walk. A task whose
+ row redaction raises is rolled back and reported ``failed``; one whose
+ post-commit cleanup raises or is skipped is reported ``cleanup_failed``;
+ both are logged and the batch continues. Re-running the same call is
+ safe and completes what is left.
+
+ Only settled tasks are redacted: PAUSED, WAITING_FOR_USER and
+ command-less PENDING tasks come back ``busy`` on every call until the
+ host cancels or settles them (see the module docstring).
+
+ ``db`` must be clean -- no pending changes and no open transaction the
+ caller still needs: each task commits or rolls back this session, so
+ caller work would be committed by the first redacted task or discarded
+ by the first busy or missing one.
+
+ Eviction of the cached agent is process-local; a host with several agent
+ worker processes evicts it on the others itself.
+
+ Blocking (database, object storage and filesystem I/O); async callers
+ run it in a worker thread.
+ """
+
+ now = datetime.now(timezone.utc)
+ redacted: list[int] = []
+ cleanup_failed: list[int] = []
+ failed: list[int] = []
+ busy: list[int] = []
+ missing: list[int] = []
+ for task_id in dict.fromkeys(task_ids):
+ try:
+ outcome = _run_on_quiescent_task(
+ db, task_id, lambda task: _redact_rows(db, task, now=now), now=now
+ )
+ except Exception:
+ logger.exception(
+ "Task %s content redaction failed and was rolled back", task_id
+ )
+ failed.append(task_id)
+ continue
+ match outcome:
+ case "busy":
+ busy.append(task_id)
+ case "missing":
+ missing.append(task_id)
+ case _RedactedRuntime() as runtime:
+ try:
+ released = _release_task_runtime(task_id, runtime)
+ except Exception:
+ logger.exception(
+ "Task %s content was redacted but its runtime or "
+ "workspace cleanup failed; re-run the redaction",
+ task_id,
+ )
+ released = False
+ if released:
+ redacted.append(task_id)
+ else:
+ cleanup_failed.append(task_id)
+ return TaskContentRedactionReport(
+ redacted=tuple(redacted),
+ cleanup_failed=tuple(cleanup_failed),
+ failed=tuple(failed),
+ busy=tuple(busy),
+ missing=tuple(missing),
+ )
+
+
+@dataclass(frozen=True)
+class TaskFileDeletionReport:
+ """Which of the requested tasks ended in which state.
+
+ ``deleted`` tasks have no uploaded files left bound to them (including
+ tasks that had none). ``failed`` tasks raised and were rolled back, but
+ the stored files deleted before the failure stay deleted: they are
+ partially cleaned and must be re-run. ``busy`` and ``missing`` mean what
+ they mean for :class:`TaskContentRedactionReport`.
+ """
+
+ deleted: tuple[int, ...] = ()
+ failed: tuple[int, ...] = ()
+ busy: tuple[int, ...] = ()
+ missing: tuple[int, ...] = ()
+
+
+def delete_task_content_files(
+ db: Session, task_ids: Sequence[int]
+) -> TaskFileDeletionReport:
+ """Delete each task's uploaded files and keep everything else.
+
+ The files-only sibling of :func:`redact_task_content`, with the same
+ contract: one transaction per settled task, the same ``busy`` refusal
+ (the host settles parked tasks first), per-task ``failed`` reporting,
+ a clean ``db`` required, idempotent re-runs. The file semantics are
+ :func:`task_deletion.delete_task_files`: a file a knowledge base still
+ uses is detached rather than deleted, each deleted file is fenced
+ against KB reuse, and a file another cleanup owner claimed is left to it.
+
+ The transcript, trace, task columns, cached agent and workspace
+ directory are untouched -- the task keeps talking about files it no
+ longer has, which is what a files-only deletion asks for. Read caches
+ are invalidated after each commit.
+
+ Blocking (database, object storage and filesystem I/O); async callers
+ run it in a worker thread.
+ """
+
+ now = datetime.now(timezone.utc)
+ deleted: list[int] = []
+ failed: list[int] = []
+ busy: list[int] = []
+ missing: list[int] = []
+ for task_id in dict.fromkeys(task_ids):
+ try:
+ outcome = _run_on_quiescent_task(
+ db, task_id, lambda task: delete_task_files(db, task), now=now
+ )
+ except Exception:
+ logger.exception(
+ "Task %s file deletion failed and was rolled back", task_id
+ )
+ failed.append(task_id)
+ continue
+ match outcome:
+ case "busy":
+ busy.append(task_id)
+ case "missing":
+ missing.append(task_id)
+ case None:
+ invalidate_task_cache(task_id)
+ deleted.append(task_id)
+ return TaskFileDeletionReport(
+ deleted=tuple(deleted),
+ failed=tuple(failed),
+ busy=tuple(busy),
+ missing=tuple(missing),
+ )
diff --git a/src/xagent/web/services/task_deletion.py b/src/xagent/web/services/task_deletion.py
index beaf74343..a40c91d95 100644
--- a/src/xagent/web/services/task_deletion.py
+++ b/src/xagent/web/services/task_deletion.py
@@ -1,9 +1,15 @@
-"""Shared, foreign-key-safe deletion of task-owned database rows."""
+"""Shared, foreign-key-safe deletion and redaction of task-owned database rows."""
from datetime import datetime, timezone
+from typing import Any
+from sqlalchemy import or_, select
from sqlalchemy.orm import Session
+from ...config import get_uploads_dir
+from ...core.tools.core.RAG_tools.storage.file_reference import file_reference_lock
+from ..models.chat_message import TaskChatMessage
+from ..models.kb_ingest_target import KBIngestTarget
from ..models.task import (
DAGExecution,
Task,
@@ -13,15 +19,24 @@ from ..models.task import (
TraceMessageBlob,
)
from ..models.task_auto_recovery import TaskAutoRecovery, TaskRecoveryEvent
+from ..models.task_channel_delivery import TaskChannelDelivery
+from ..models.task_command import TaskExecutionCommand
+from ..models.task_execution_event import TaskExecutionEvent
from ..models.task_interaction import TaskInteractionRequest
from ..models.task_runtime_secret import TaskRuntimeSecret
from ..models.trigger import TriggerRun, TriggerRunStatus
+from ..models.uploaded_file import UploadedFile
+from .kb_file_service import find_referenced_file_ids
+from .kb_reference_protection import record_cleanup_fence
from .task_file_lifecycle import (
DetachmentReason,
detach_task_files,
lock_attachment_task,
)
from .task_interaction_schema import interaction_requests_table_exists
+from .task_retention import RETENTION_LIVE_COMMAND_STATUSES
+from .task_runtime import PROMPT_CONTEXT_AGENT_CONFIG_KEY
+from .uploaded_file_store import UploadedFileStore, UploadedFileVersionConflict
# TriggerRun error for a run whose task was deleted before it settled.
TASK_DELETED_TRIGGER_ERROR = "Task deleted before its run finished."
@@ -53,29 +68,23 @@ def _fail_unsettled_trigger_runs(db: Session, task_id: int) -> None:
)
-def purge_task_rows(
- db: Session,
- *,
- task_id: int,
- detached_reason: DetachmentReason,
-) -> bool:
- """Delete one task and its non-cascading rows in a caller-owned transaction.
+def _delete_task_content_rows(db: Session, task_id: int) -> bool:
+ """Delete the content rows ``purge_task_rows`` and ``redact_task_rows`` share.
- ``detached_reason`` is required: ``task_deleted`` for deletion/expiry or
- ``task_create_failed`` for failed-create compensation. Marking shares this
- transaction with deletion; retained file bytes are reclaimed later.
+ Covers every task-owned table whose rows carry execution content and that
+ the task row's own deletion would not reliably cascade: interaction
+ requests, auto-recovery state, the trace and its two blob tables, the DAG
+ execution and runtime secrets. Chat messages and execution events are
+ left to the callers: the task purge relies on the ORM cascade and ``ON
+ DELETE CASCADE`` for them, and the redaction deletes them itself.
+ Connector runtime context is the purge's alone: it is non-secret routing
+ input a redacted task's next turn is validated against, not content.
- ``task_interaction_requests`` rows, unlike ``UploadedFile``, are deleted
- outright: the CASCADE on ``task_id`` would remove them anyway, and the
- delete must run before the ``trace_events`` delete below (see the
- ordering comment at that call).
+ Returns whether any trace row was removed. The caller holds the task row
+ lock and owns the transaction. Statement order is load-bearing; the
+ comments below say why.
"""
- task = lock_attachment_task(db, task_id, deleting=True)
- if task is None:
- return False
- detach_task_files(db, task_id=task_id, reason=detached_reason)
-
# NULL the checkpoint pointer columns before the trace_events delete
# below: last_checkpoint_trace_event_id FKs to trace_events.id, so a
# task still pointing at a row would block (or, without DB-level
@@ -83,10 +92,14 @@ def purge_task_rows(
# attribute assignment, because this session has autoflush disabled --
# an attribute assignment would not reach the database until a later
# flush, by which point the trace_events delete has already run.
+ # ``updated_at`` is pinned: the redaction keeps this row, and its
+ # ``updated_at`` doubles as the v1 ``completed_at`` and as a usage
+ # window key, neither of which content removal may move.
db.query(Task).filter(Task.id == task_id).update(
{
Task.last_checkpoint_event_id: None,
Task.last_checkpoint_trace_event_id: None,
+ Task.updated_at: Task.updated_at,
},
synchronize_session=False,
)
@@ -119,7 +132,6 @@ def purge_task_rows(
# interaction table: an Alembic upgrade can stop short of these tables,
# but ``Base.metadata.create_all`` runs right after ``try_upgrade_db`` on
# every startup, so they exist before the process serves anything.
- _fail_unsettled_trigger_runs(db, task_id)
db.query(TaskRecoveryEvent).filter(TaskRecoveryEvent.task_id == task_id).delete(
synchronize_session=False
)
@@ -127,23 +139,252 @@ def purge_task_rows(
synchronize_session=False
)
- db.query(TraceCheckpointBlob).filter(TraceCheckpointBlob.task_id == task_id).delete(
- synchronize_session=False
+ trace_rows = sum(
+ db.query(model)
+ .filter(model.task_id == task_id)
+ .delete(synchronize_session=False)
+ for model in (TraceCheckpointBlob, TraceMessageBlob, TraceEvent)
)
- db.query(TraceMessageBlob).filter(TraceMessageBlob.task_id == task_id).delete(
- synchronize_session=False
- )
- db.query(TraceEvent).filter(TraceEvent.task_id == task_id).delete(
+ db.query(DAGExecution).filter(DAGExecution.task_id == task_id).delete(
synchronize_session=False
)
- db.query(DAGExecution).filter(DAGExecution.task_id == task_id).delete(
+ db.query(TaskRuntimeSecret).filter(TaskRuntimeSecret.task_id == task_id).delete(
synchronize_session=False
)
+ return trace_rows > 0
+
+
+def purge_task_rows(
+ db: Session,
+ *,
+ task_id: int,
+ detached_reason: DetachmentReason,
+) -> bool:
+ """Delete one task and its non-cascading rows in a caller-owned transaction.
+
+ ``detached_reason`` is required: ``task_deleted`` for deletion/expiry or
+ ``task_create_failed`` for failed-create compensation. Marking shares this
+ transaction with deletion; retained file bytes are reclaimed later.
+
+ ``task_interaction_requests`` rows, unlike ``UploadedFile``, are deleted
+ outright: the CASCADE on ``task_id`` would remove them anyway, and the
+ delete must run before the ``trace_events`` delete (see
+ :func:`_delete_task_content_rows`).
+ """
+
+ task = lock_attachment_task(db, task_id, deleting=True)
+ if task is None:
+ return False
+ detach_task_files(db, task_id=task_id, reason=detached_reason)
+ _fail_unsettled_trigger_runs(db, task_id)
+ _delete_task_content_rows(db, task_id)
db.query(TaskConnectorRuntimeContext).filter(
TaskConnectorRuntimeContext.task_id == task_id
).delete(synchronize_session=False)
- db.query(TaskRuntimeSecret).filter(TaskRuntimeSecret.task_id == task_id).delete(
- synchronize_session=False
- )
db.delete(task)
return True
+
+
+def delete_task_files(db: Session, task: Task) -> None:
+ """Delete one task's uploaded files in a caller-owned transaction.
+
+ Rows, durable objects and local bytes. ``task`` must already be locked in
+ this transaction through :func:`lock_attachment_task` with
+ ``deleting=True``, which fences new attachments, and the caller must have
+ established that it is not executing. The rest of the task -- transcript,
+ trace, workspace, columns -- is untouched; :func:`redact_task_rows` calls
+ this as its file step. Idempotent: a second run finds no files.
+
+ Unlike :func:`detach_task_files`, nothing is retained -- except a file a
+ knowledge base still uses. A chat attachment can back a KB document (KB
+ ingest finds the upload by ``file_id`` alone), so a file that a KB
+ document references, or that a live KB ingest targets, is detached from
+ the task the way task deletion detaches files, and the KB keeps its
+ source. The check runs under the KB reference lock, the same fence
+ orphan GC and KB cleanup take, and each deleted file gets a cleanup fence
+ so a later ingest cannot adopt its id. The lock is released before the
+ caller commits, so an ingest that publishes in that window can still
+ lose its source; the KB delete paths accept the same window.
+
+ The bytes go *inside* the caller's transaction, before it commits,
+ through the same :meth:`UploadedFileStore.delete` the KB and file routes
+ use: the object delete is idempotent, so a transaction that fails
+ afterwards leaves rows whose re-run deletes them, while deleting after
+ the commit would leave an object with no row left to find it by.
+
+ Rows another owner has claimed (``compensating``) are skipped, and so is
+ a row that owner claims between this read and the delete
+ (:class:`UploadedFileVersionConflict`): the claimant deletes the row and
+ every resource it names, as in ``kb_file_service``.
+ """
+
+ task_id = int(task.id)
+ records = (
+ db.query(UploadedFile)
+ .filter(
+ UploadedFile.task_id == task_id,
+ UploadedFile.storage_status != "compensating",
+ )
+ .all()
+ )
+ if not records:
+ return
+ file_ids = [str(record.file_id) for record in records]
+ store = UploadedFileStore(db)
+ uploads_root = get_uploads_dir()
+ with file_reference_lock(file_ids):
+ ingesting = {
+ str(file_id)
+ for (file_id,) in db.query(KBIngestTarget.file_id).filter(
+ KBIngestTarget.file_id.in_(file_ids),
+ KBIngestTarget.deleted_at.is_(None),
+ )
+ }
+ kept = ingesting | find_referenced_file_ids(file_ids)
+ for record in records:
+ if str(record.file_id) in kept:
+ continue
+ try:
+ store.delete(record, local_root=uploads_root)
+ except UploadedFileVersionConflict:
+ continue
+ record_cleanup_fence(db, str(record.file_id))
+ if kept:
+ db.query(UploadedFile).filter(
+ UploadedFile.task_id == task_id, UploadedFile.file_id.in_(kept)
+ ).update(
+ {
+ UploadedFile.task_id: None,
+ UploadedFile.detached_reason: "task_deleted",
+ UploadedFile.detached_at: datetime.now(timezone.utc),
+ },
+ synchronize_session=False,
+ )
+
+
+#: ``tasks.agent_config`` keys that carry content or personal data rather
+#: than routing or authorization: the prompt reference data a run is given,
+#: and the widget creator's IP. Every other key is identity the task's later
+#: reads and turns still need (auth mode, guest id, runtime bindings, ...).
+_REDACTED_AGENT_CONFIG_KEYS = frozenset(
+ {PROMPT_CONTEXT_AGENT_CONFIG_KEY, "widget_client_ip"}
+)
+
+
+def redact_task_rows(db: Session, task: Task, *, now: datetime) -> None:
+ """Delete one task's content but keep its row, in a caller-owned transaction.
+
+ ``task`` must already be locked in this transaction through
+ :func:`lock_attachment_task` with ``deleting=True``, which also fences new
+ attachments, and the caller must have established that it is not
+ executing (see ``task_content_redaction``).
+
+ What goes: every row :func:`_delete_task_content_rows` removes, the chat
+ transcript and execution events, the task's uploaded files (rows *and*
+ stored bytes, see :func:`delete_task_files`), the payload, result and
+ error of its execution commands, the payload snapshots of the trigger
+ runs that started it, the content keys of ``agent_config``
+ (:data:`_REDACTED_AGENT_CONFIG_KEYS`), and every content-bearing ``Task``
+ column (title, description, latest input/output, error, structured
+ result, process-mode description and examples).
+
+ What stays: the row and everything metering, identity, routing or
+ authorization reads -- ids, owner, status, timestamps, token counters and
+ usage details, model and agent identifiers, the remaining ``agent_config``
+ keys, channel and source fields, the connector runtime context and
+ selected refs (non-secret routing input a later turn is validated
+ against), uploads a knowledge base still uses (detached instead, see
+ :func:`delete_task_files`), the trigger run rows themselves, and the
+ event sequence counter, so a later turn keeps numbering monotonically.
+ ``updated_at`` is pinned (see :func:`_delete_task_content_rows`).
+ ``traces_expired_at`` is stamped with ``now`` when there was a trace to
+ remove: it is the marker trace readers already honour for "steps before
+ this moment were removed", and a re-run that removes nothing keeps it.
+
+ Command rows are blanked rather than deleted: their identity is the
+ resend dedupe key, and a deleted row would let a client's retry of an
+ old command execute it again. A retry now conflicts on the blank payload
+ instead of replaying. Only settled commands are blanked; one still owed
+ execution keeps its payload. Their pending channel deliveries are
+ discarded in the same step: the delivery worker reads the destination
+ channel out of the command payload, so a pending delivery of a blanked
+ command could never be claimed and would sit at the head of its
+ channel's queue forever -- and the reply it would carry belongs to the
+ deleted conversation anyway. A delivery a sender has claimed under a
+ live lease is left to it: that send has already read the reply and may
+ still post it after the redaction commits.
+
+ Idempotent: a second run finds nothing to delete and rewrites the same
+ blank values.
+ """
+
+ task_id = int(task.id)
+ delete_task_files(db, task)
+ had_trace = _delete_task_content_rows(db, task_id)
+ db.query(TaskChatMessage).filter(TaskChatMessage.task_id == task_id).delete(
+ synchronize_session=False
+ )
+ db.query(TaskExecutionEvent).filter(TaskExecutionEvent.task_id == task_id).delete(
+ synchronize_session=False
+ )
+ task_commands = select(TaskExecutionCommand.id).where(
+ TaskExecutionCommand.task_id == task_id
+ )
+ db.query(TaskChannelDelivery).filter(
+ TaskChannelDelivery.command_id.in_(task_commands),
+ TaskChannelDelivery.status == "pending",
+ # Not a delivery a sender holds under a live lease: that sender has
+ # already read the reply and settles it itself. An expired claim is
+ # discarded, since the next claim would read the blanked payload.
+ or_(
+ TaskChannelDelivery.claim_token.is_(None),
+ TaskChannelDelivery.available_at <= now,
+ ),
+ ).update(
+ {
+ TaskChannelDelivery.status: "discarded",
+ TaskChannelDelivery.claim_token: None,
+ },
+ synchronize_session=False,
+ )
+ db.query(TaskExecutionCommand).filter(
+ TaskExecutionCommand.task_id == task_id,
+ # A command still owed execution keeps its payload. The caller's
+ # quiescence check already refuses such a task, but on SQLite, where
+ # ``FOR UPDATE`` is a no-op, one can be enqueued in between, and it
+ # must not then execute an empty payload.
+ TaskExecutionCommand.status.not_in(RETENTION_LIVE_COMMAND_STATUSES),
+ ).update(
+ {
+ TaskExecutionCommand.payload: {},
+ TaskExecutionCommand.result: None,
+ TaskExecutionCommand.error: None,
+ },
+ synchronize_session=False,
+ )
+ db.query(TriggerRun).filter(TriggerRun.task_id == task_id).update(
+ {TriggerRun.payload_snapshot: None}, synchronize_session=False
+ )
+ values: dict[Any, Any] = {
+ # NOT NULL; every other content column is nullable.
+ Task.title: "",
+ Task.description: None,
+ Task.input: None,
+ Task.output: None,
+ Task.error_message: None,
+ Task.structured_output_record: None,
+ Task.process_description: None,
+ Task.examples: None,
+ # Names the interaction row deleted above.
+ Task.interaction_protocol_version: None,
+ Task.updated_at: Task.updated_at,
+ }
+ if isinstance(task.agent_config, dict):
+ values[Task.agent_config] = {
+ key: value
+ for key, value in task.agent_config.items()
+ if key not in _REDACTED_AGENT_CONFIG_KEYS
+ }
+ if had_trace:
+ values[Task.traces_expired_at] = now
+ db.query(Task).filter(Task.id == task_id).update(values, synchronize_session=False)
diff --git a/tests/web/api/v1/test_task_content_redaction.py b/tests/web/api/v1/test_task_content_redaction.py
new file mode 100644
index 000000000..8c63fe7ed
--- /dev/null
+++ b/tests/web/api/v1/test_task_content_redaction.py
@@ -0,0 +1,820 @@
+"""Content redaction of a task whose row and usage must survive.
+
+``redact_task_content`` is what a host calls when a user deletes their
+conversation history while billing keeps reading the task's token counters.
+These tests pin the split it promises -- every content row, file and object
+gone; the task row, its metering columns and ``updated_at`` intact -- plus
+idempotency, the busy refusal, and that the read surfaces still answer for
+a redacted task rather than failing on missing content.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any, Iterator
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from tests.shared.auth_database import auth_db_override
+from tests.shared.execution_scope import register_scope_resolver
+from xagent.core.execution_scope import set_execution_scope_snapshot_loader
+from xagent.core.file_storage.factory import (
+ get_unscoped_file_storage,
+ get_user_file_storage,
+)
+from xagent.web.api.chat import chat_router
+from xagent.web.models.auth_database import get_auth_db
+from xagent.web.models.chat_message import TaskChatMessage
+from xagent.web.models.database import get_db
+from xagent.web.models.kb_ingest_target import KBIngestTarget
+from xagent.web.models.task import (
+ DAGExecution,
+ Task,
+ TaskConnectorRuntimeContext,
+ TaskStatus,
+ TraceCheckpointBlob,
+ TraceEvent,
+ TraceMessageBlob,
+)
+from xagent.web.models.task_auto_recovery import TaskAutoRecovery, TaskRecoveryEvent
+from xagent.web.models.task_command import TaskExecutionCommand
+from xagent.web.models.task_execution_event import TaskExecutionEvent
+from xagent.web.models.task_interaction import TaskInteractionRequest
+from xagent.web.models.task_runtime_secret import TaskRuntimeSecret
+from xagent.web.models.uploaded_file import UploadedFile
+from xagent.web.models.uploaded_file_cleanup_fence import UploadedFileCleanupFence
+from xagent.web.services import task_content_redaction, task_deletion
+from xagent.web.services.agent_service_manager import get_agent_manager
+from xagent.web.services.execution_scope_snapshot import (
+ load_task_execution_scope_snapshot,
+)
+from xagent.web.services.task_command_transport import (
+ COMMAND_COMPLETED,
+ COMMAND_PENDING,
+)
+from xagent.web.services.task_content_redaction import (
+ TaskContentRedactionReport,
+ TaskFileDeletionReport,
+ delete_task_content_files,
+ redact_task_content,
+)
+from xagent.web.services.uploaded_file_store import (
+ UploadedFileStore,
+ UploadedFileVersionConflict,
+)
+
+from ...services.task_interaction_schema_shared import make_row
+from ..conftest import _admin_headers, _direct_db_session, _override_get_db, client
+from .test_v1_delete_task import (
+ _bearer,
+ _create_agent_with_key,
+ _create_task,
+ _force_status,
+)
+
+pytestmark = pytest.mark.usefixtures("_test_db")
+
+_chat_app = FastAPI()
+_chat_app.include_router(chat_router)
+_chat_app.dependency_overrides[get_db] = _override_get_db
+_chat_app.dependency_overrides[get_auth_db] = auth_db_override(_override_get_db)
+chat_client = TestClient(_chat_app)
+
+#: The content columns the redaction blanks, with the value each is seeded at.
+CONTENT_COLUMNS: dict[str, Any] = {
+ "title": "secret title",
+ "description": "secret description",
+ "input": "secret input",
+ "output": "secret output",
+ "error_message": "secret error",
+ "structured_output_record": {"output": "secret"},
+ "process_description": "secret process",
+ "examples": [{"input": "secret"}],
+}
+
+#: Columns billing and routing read, with the value each is seeded at.
+KEPT_COLUMNS: dict[str, Any] = {
+ "input_tokens": 120,
+ "output_tokens": 45,
+ "total_tokens": 165,
+ "llm_calls": 3,
+ "token_usage_details": {"model-a": {"input_tokens": 120}},
+ "model_id": "model-a",
+ "model_name": "provider/model-a",
+ "completion_outcome": "completed",
+}
+
+UPDATED_AT = datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
+
+
[email protected](autouse=True)
+def mock_start_task() -> Iterator[None]:
+ with patch(
+ "xagent.web.services.task_orchestrator._schedule_bg",
+ new=MagicMock(),
+ ):
+ yield
+
+
[email protected](autouse=True)
+def _roots(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
+ """Point uploads and durable storage at ``tmp_path``; yields the uploads root."""
+ uploads = tmp_path / "uploads"
+ uploads.mkdir()
+ monkeypatch.setenv("XAGENT_UPLOADS_DIR", str(uploads))
+ monkeypatch.setenv("XAGENT_EXTERNAL_UPLOAD_DIRS", "")
+ monkeypatch.setenv("XAGENT_FILE_STORAGE_URI", (tmp_path / "objects").as_uri())
+ get_unscoped_file_storage.cache_clear()
+ register_scope_resolver(None)
+ set_execution_scope_snapshot_loader(load_task_execution_scope_snapshot)
+ get_agent_manager()._agents.clear()
+
+ yield uploads
+
+ set_execution_scope_snapshot_loader(None)
+ get_unscoped_file_storage.cache_clear()
+
+
+def _object_exists(owner_id: int, storage_key: str) -> bool:
+ return get_user_file_storage(owner_id).exists(storage_key)
+
+
+def _settled_task(full_key: str, agent_id: int) -> int:
+ """A COMPLETED SDK task carrying every content column and usage counter."""
+ task_id = _create_task(full_key, agent_id)
+ _force_status(task_id, TaskStatus.COMPLETED)
+ db = _direct_db_session()
+ try:
+ db.query(Task).filter(Task.id == task_id).update(
+ {**CONTENT_COLUMNS, **KEPT_COLUMNS, "updated_at": UPDATED_AT}
+ )
+ db.commit()
+ finally:
+ db.close()
+ return task_id
+
+
+def _seed_content(task_id: int, uploads: Path) -> tuple[str, Path, Path]:
+ """One row of every content table, an uploaded file and a workspace.
+
+ Returns the file's storage key, its local path and the workspace dir.
+ """
+ db = _direct_db_session()
+ try:
+ task = db.query(Task).filter(Task.id == task_id).one()
+ owner_id = int(task.user_id)
+ trace = TraceEvent(
+ task_id=task_id,
+ event_id=f"event-{task_id}",
+ event_type="agent_execution_checkpoint",
+ timestamp=datetime.now(UTC),
+ data={"content": "secret trace"},
+ )
+ db.add(trace)
+ db.flush()
+ db.add_all(
+ [
+ TraceMessageBlob(
+ task_id=task_id,
+ execution_id="exec",
+ message_hash=f"m{task_id}",
+ message_data={"content": "secret"},
+ message_bytes=8,
+ ),
+ TraceCheckpointBlob(
+ task_id=task_id,
+ execution_id="exec",
+ blob_kind="messages",
+ blob_hash=f"c{task_id}",
+ blob_data={"content": "secret"},
+ blob_bytes=8,
+ ),
+ DAGExecution(task_id=task_id, current_plan={"goal": "secret"}),
+ TaskChatMessage(
+ task_id=task_id,
+ user_id=owner_id,
+ role="user",
+ content="secret message",
+ message_type="user_message",
+ ),
+ TaskExecutionEvent(
+ event_id=f"exec-event-{task_id}",
+ task_id=task_id,
+ sequence=1,
+ scope_id="root",
+ idempotency_key="k1",
+ kind="assistant_message",
+ payload_version=1,
+ payload={"content": "secret"},
+ occurred_at=datetime.now(UTC),
+ ),
+ TaskConnectorRuntimeContext(
+ task_id=task_id,
+ connector_type="mcp",
+ connector_id=1,
+ context={"account": "secret"},
+ ),
+ TaskRuntimeSecret(
+ task_id=task_id,
+ turn_id="turn",
+ run_id="run",
+ owner_subject="owner",
+ ciphertext="secret",
+ ),
+ TaskAutoRecovery(
+ task_id=task_id,
+ run_id="run",
+ reason="worker_lost",
+ state="exhausted",
+ paused_state_version=1,
+ interrupted_at=datetime.now(UTC),
+ episode_started_at=datetime.now(UTC),
+ ),
+ TaskRecoveryEvent(task_id=task_id, run_id="run", event="interrupted"),
+ ]
+ )
+ # An active interaction anchored on the trace row: the ordering
+ # that keeps its CHECK satisfied is what this covers.
+ db.add(
+ TaskInteractionRequest(
+ **make_row(task_id=task_id, resume_trace_event_id=int(trace.id), db=db)
+ )
+ )
+ db.add(
+ TaskExecutionCommand(
+ task_id=task_id,
+ command_id=f"turn-{task_id}",
+ kind="message",
+ payload={"content": "secret"},
+ result={"output": "secret"},
+ error="secret",
+ status=COMMAND_COMPLETED,
+ )
+ )
+ db.query(Task).filter(Task.id == task_id).update(
+ {
+ "last_checkpoint_event_id": trace.event_id,
+ "last_checkpoint_trace_event_id": trace.id,
+ "interaction_protocol_version": 1,
+ "updated_at": UPDATED_AT,
+ }
+ )
+ db.commit()
+
+ local = uploads / f"user_{owner_id}" / "uploads" / f"attachment-{task_id}.txt"
+ local.parent.mkdir(parents=True, exist_ok=True)
+ local.write_text("secret file")
+ record = UploadedFileStore(db).create_from_local_path(
+ local_path=local, user_id=owner_id, task_id=task_id
+ )
+ db.commit()
+ storage_key = str(record.storage_key)
+ assert _object_exists(owner_id, storage_key)
+ finally:
+ db.close()
+
+ workspace = uploads / f"web_task_{task_id}"
+ (workspace / "output").mkdir(parents=True)
+ (workspace / "output" / "result.txt").write_text("secret output file")
+ return storage_key, local, workspace
+
+
+def _add_file(task_id: int, uploads: Path, name: str) -> Path:
+ """One more uploaded file bound to ``task_id``; returns its local path."""
+ db = _direct_db_session()
+ try:
+ owner_id = int(db.query(Task.user_id).filter(Task.id == task_id).one()[0])
+ local = uploads / f"user_{owner_id}" / "uploads" / f"{name}-{task_id}.txt"
+ local.parent.mkdir(parents=True, exist_ok=True)
+ local.write_text("secret file")
+ UploadedFileStore(db).create_from_local_path(
+ local_path=local, user_id=owner_id, task_id=task_id
+ )
+ db.commit()
+ return local
+ finally:
+ db.close()
+
+
+def _file_ids(task_id: int) -> list[str]:
+ db = _direct_db_session()
+ try:
+ return [
+ str(file_id)
+ for (file_id,) in db.query(UploadedFile.file_id)
+ .filter(UploadedFile.task_id == task_id)
+ .order_by(UploadedFile.id)
+ ]
+ finally:
+ db.close()
+
+
+def _content_counts(task_id: int) -> dict[str, int]:
+ db = _direct_db_session()
+ try:
+ return {
+ model.__tablename__: db.query(model)
+ .filter(model.task_id == task_id)
+ .count()
+ for model in (
+ TraceEvent,
+ TraceMessageBlob,
+ TraceCheckpointBlob,
+ DAGExecution,
+ TaskChatMessage,
+ TaskExecutionEvent,
+ TaskRuntimeSecret,
+ TaskAutoRecovery,
+ TaskRecoveryEvent,
+ TaskInteractionRequest,
+ UploadedFile,
+ )
+ }
+ finally:
+ db.close()
+
+
+def _redact(task_ids: list[int]) -> TaskContentRedactionReport:
+ db = _direct_db_session()
+ try:
+ return redact_task_content(db, task_ids)
+ finally:
+ db.close()
+
+
+def test_redaction_removes_content_and_keeps_the_task_and_its_usage(
+ _roots: Path,
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ bystander_id = _settled_task(full_key, agent_id)
+ storage_key, local, workspace = _seed_content(task_id, _roots)
+ _seed_content(bystander_id, _roots)
+ [file_id] = _file_ids(task_id)
+
+ report = _redact([task_id, task_id, 9_000_001])
+
+ assert report == TaskContentRedactionReport(
+ redacted=(task_id,), busy=(), missing=(9_000_001,)
+ )
+ assert set(_content_counts(task_id).values()) == {0}
+ assert not local.exists()
+ assert not workspace.exists()
+ db = _direct_db_session()
+ try:
+ # The deleted file's id is fenced so a later KB ingest cannot adopt it.
+ assert db.get(UploadedFileCleanupFence, file_id) is not None
+ # Non-secret routing input the next turn is validated against.
+ assert (
+ db.query(TaskConnectorRuntimeContext)
+ .filter(TaskConnectorRuntimeContext.task_id == task_id)
+ .count()
+ == 1
+ )
+ finally:
+ db.close()
+ db = _direct_db_session()
+ try:
+ task = db.query(Task).filter(Task.id == task_id).one()
+ owner_id = int(task.user_id)
+ assert not _object_exists(owner_id, storage_key)
+ assert {name: getattr(task, name) for name in CONTENT_COLUMNS} == {
+ "title": "",
+ **{name: None for name in CONTENT_COLUMNS if name != "title"},
+ }
+ assert {name: getattr(task, name) for name in KEPT_COLUMNS} == KEPT_COLUMNS
+ assert task.status == TaskStatus.COMPLETED
+ assert task.agent_id == agent_id
+ assert task.updated_at.replace(tzinfo=UTC) == UPDATED_AT
+ assert task.traces_expired_at is not None
+ assert task.last_checkpoint_event_id is None
+ assert task.last_checkpoint_trace_event_id is None
+ assert task.interaction_protocol_version is None
+ commands = (
+ db.query(TaskExecutionCommand)
+ .filter(TaskExecutionCommand.task_id == task_id)
+ .all()
+ )
+ assert commands
+ assert all(
+ (command.payload, command.result, command.error) == ({}, None, None)
+ for command in commands
+ )
+ finally:
+ db.close()
+ assert 0 not in _content_counts(bystander_id).values()
+
+
+def test_redaction_is_idempotent(_roots: Path) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _seed_content(task_id, _roots)
+
+ first = _redact([task_id])
+ second = _redact([task_id])
+
+ assert first == second == TaskContentRedactionReport(redacted=(task_id,))
+ assert set(_content_counts(task_id).values()) == {0}
+ db = _direct_db_session()
+ try:
+ task = db.query(Task).filter(Task.id == task_id).one()
+ assert task.input_tokens == KEPT_COLUMNS["input_tokens"]
+ assert task.updated_at.replace(tzinfo=UTC) == UPDATED_AT
+ finally:
+ db.close()
+
+
+def test_a_cleanup_failure_is_reported_and_the_batch_continues(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ failing_id = _settled_task(full_key, agent_id)
+ next_id = _settled_task(full_key, agent_id)
+ _seed_content(failing_id, _roots)
+ _seed_content(next_id, _roots)
+ manager = get_agent_manager()
+ remove_agent = manager.remove_agent
+
+ def flaky_remove_agent(task_id: int, *args: Any, **kwargs: Any) -> bool:
+ if task_id == failing_id:
+ raise OSError("workspace is busy")
+ return remove_agent(task_id, *args, **kwargs)
+
+ monkeypatch.setattr(manager, "remove_agent", flaky_remove_agent)
+
+ report = _redact([failing_id, next_id])
+
+ assert report == TaskContentRedactionReport(
+ redacted=(next_id,), cleanup_failed=(failing_id,)
+ )
+ # The rows were committed before the cleanup ran.
+ assert set(_content_counts(failing_id).values()) == {0}
+ assert (_roots / f"web_task_{failing_id}").exists()
+ assert not (_roots / f"web_task_{next_id}").exists()
+
+
[email protected]("new_turn_after_commit", [False, True])
+def test_cleanup_spares_a_runtime_a_later_turn_acquired(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch, new_turn_after_commit: bool
+) -> None:
+ """The eviction is fenced on the runtime identity read under the lock.
+
+ A turn that acquires the runtime between the commit and the cleanup owns
+ the cached agent and its workspace; the cleanup must leave both alone.
+ """
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _, _, workspace = _seed_content(task_id, _roots)
+ manager = get_agent_manager()
+ cached_agent = MagicMock()
+ manager._agents[task_id] = cached_agent
+ manager._agent_run_generations[task_id] = 1
+
+ if new_turn_after_commit:
+
+ def acquire_after_commit(_task_id: int) -> None:
+ # Runs after the commit, before the eviction: a new acquisition.
+ manager._agent_run_generations[task_id] = 2
+
+ monkeypatch.setattr(
+ task_content_redaction, "invalidate_task_cache", acquire_after_commit
+ )
+
+ report = _redact([task_id])
+
+ if new_turn_after_commit:
+ # The workspace keeps pre-redaction files: the host must re-run.
+ assert report == TaskContentRedactionReport(cleanup_failed=(task_id,))
+ else:
+ assert report == TaskContentRedactionReport(redacted=(task_id,))
+ if new_turn_after_commit:
+ assert manager._agents[task_id] is cached_agent
+ cached_agent.cleanup_workspace.assert_not_called()
+ assert workspace.exists()
+ else:
+ assert task_id not in manager._agents
+ cached_agent.cleanup_workspace.assert_called_once()
+ manager._agents.pop(task_id, None)
+ manager._agent_run_generations.pop(task_id, None)
+
+
+def test_a_storage_failure_rolls_back_that_task_and_the_batch_continues(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ failing_id = _settled_task(full_key, agent_id)
+ next_id = _settled_task(full_key, agent_id)
+ _seed_content(failing_id, _roots)
+ _seed_content(next_id, _roots)
+ before = _content_counts(failing_id)
+ delete = UploadedFileStore.delete
+
+ def flaky_delete(self: UploadedFileStore, record: Any, **kwargs: Any) -> None:
+ if record.task_id == failing_id:
+ raise OSError("object storage unavailable")
+ delete(self, record, **kwargs)
+
+ monkeypatch.setattr(UploadedFileStore, "delete", flaky_delete)
+
+ report = _redact([failing_id, next_id])
+
+ assert report == TaskContentRedactionReport(
+ redacted=(next_id,), failed=(failing_id,)
+ )
+ assert _content_counts(failing_id) == before
+ assert set(_content_counts(next_id).values()) == {0}
+
+
+def test_a_file_claimed_by_another_owner_is_left_to_it(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A version conflict means a cleanup claimant owns the file now."""
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _seed_content(task_id, _roots)
+
+ def claimed(self: UploadedFileStore, record: Any, **kwargs: Any) -> None:
+ raise UploadedFileVersionConflict("claimed before deletion")
+
+ monkeypatch.setattr(UploadedFileStore, "delete", claimed)
+
+ report = _redact([task_id])
+
+ assert report == TaskContentRedactionReport(redacted=(task_id,))
+ counts = _content_counts(task_id)
+ assert counts.pop(UploadedFile.__tablename__) == 1
+ assert set(counts.values()) == {0}
+
+
+def test_a_file_a_knowledge_base_references_is_detached_not_deleted(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ storage_key, local, _ = _seed_content(task_id, _roots)
+ db = _direct_db_session()
+ try:
+ record = db.query(UploadedFile).filter(UploadedFile.task_id == task_id).one()
+ file_id, owner_id = str(record.file_id), int(record.user_id)
+ finally:
+ db.close()
+ monkeypatch.setattr(
+ task_deletion,
+ "find_referenced_file_ids",
+ lambda file_ids: {file_id} & set(file_ids),
+ )
+
+ report = _redact([task_id])
+
+ assert report == TaskContentRedactionReport(redacted=(task_id,))
+ assert local.exists()
+ assert _object_exists(owner_id, storage_key)
+ db = _direct_db_session()
+ try:
+ kept = db.query(UploadedFile).filter(UploadedFile.file_id == file_id).one()
+ assert (kept.task_id, kept.detached_reason) == (None, "task_deleted")
+ finally:
+ db.close()
+
+
+def test_a_partial_storage_failure_is_reported_and_a_rerun_finishes(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A failure on the second file rolls the rows back, but the first
+ file's bytes are already gone: the task is partially cleaned."""
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _, first_local, _ = _seed_content(task_id, _roots)
+ second_local = _add_file(task_id, _roots, "second")
+ first_id, second_id = _file_ids(task_id)
+ delete = UploadedFileStore.delete
+
+ def fail_second(self: UploadedFileStore, record: Any, **kwargs: Any) -> None:
+ if str(record.file_id) == second_id:
+ raise OSError("object storage unavailable")
+ delete(self, record, **kwargs)
+
+ with monkeypatch.context() as patched:
+ patched.setattr(UploadedFileStore, "delete", fail_second)
+ report = _redact([task_id])
+
+ assert report == TaskContentRedactionReport(failed=(task_id,))
+ assert _file_ids(task_id) == [first_id, second_id]
+ assert not first_local.exists()
+ assert second_local.exists()
+
+ assert _redact([task_id]) == TaskContentRedactionReport(redacted=(task_id,))
+ assert _file_ids(task_id) == []
+ assert not second_local.exists()
+
+
+def test_a_file_a_live_kb_ingest_targets_is_detached_not_deleted(
+ _roots: Path,
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ storage_key, local, _ = _seed_content(task_id, _roots)
+ [file_id] = _file_ids(task_id)
+ db = _direct_db_session()
+ try:
+ owner_id = int(db.query(Task.user_id).filter(Task.id == task_id).one()[0])
+ db.add(
+ KBIngestTarget(
+ user_id=owner_id,
+ collection="kb",
+ target_path="attachment.txt",
+ file_id=file_id,
+ latest_file_sha256="0" * 64,
+ )
+ )
+ db.commit()
+ finally:
+ db.close()
+
+ assert _redact([task_id]) == TaskContentRedactionReport(redacted=(task_id,))
+
+ assert local.exists()
+ assert _object_exists(owner_id, storage_key)
+ db = _direct_db_session()
+ try:
+ kept = db.query(UploadedFile).filter(UploadedFile.file_id == file_id).one()
+ assert (kept.task_id, kept.detached_reason) == (None, "task_deleted")
+ assert db.get(UploadedFileCleanupFence, file_id) is None
+ finally:
+ db.close()
+
+
+def test_an_unresolvable_workspace_scope_still_evicts_the_cached_agent(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _seed_content(task_id, _roots)
+ manager = get_agent_manager()
+ cached_agent = MagicMock()
+ manager._agents[task_id] = cached_agent
+
+ def unresolvable(*args: Any, **kwargs: Any) -> None:
+ raise RuntimeError("execution scope did not resolve")
+
+ monkeypatch.setattr(
+ task_content_redaction, "capture_workspace_cleanup_target", unresolvable
+ )
+
+ report = _redact([task_id])
+
+ assert report == TaskContentRedactionReport(cleanup_failed=(task_id,))
+ assert task_id not in manager._agents
+ cached_agent.cleanup_workspace.assert_called_once()
+ assert set(_content_counts(task_id).values()) == {0}
+
+
+#: Task states the redaction must refuse. The parked ones (paused, waiting
+#: for the user, pending with nothing queued) never settle by themselves; the
+#: host cancels them first.
+BUSY_STATES: dict[str, dict[str, Any]] = {
+ "running": {"status": TaskStatus.RUNNING},
+ "paused": {"status": TaskStatus.PAUSED},
+ "waiting_for_user": {"status": TaskStatus.WAITING_FOR_USER},
+ "pending_without_command": {"status": TaskStatus.PENDING},
+ "live_lease": {"lease_expires_at": datetime.now(UTC) + timedelta(hours=1)},
+}
+
+
[email protected]("state", [*BUSY_STATES, "pending_command"])
+def test_redaction_leaves_a_busy_task_untouched(_roots: Path, state: str) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _seed_content(task_id, _roots)
+ db = _direct_db_session()
+ try:
+ if state in BUSY_STATES:
+ db.query(Task).filter(Task.id == task_id).update(BUSY_STATES[state])
+ else:
+ db.add(
+ TaskExecutionCommand(
+ task_id=task_id,
+ command_id="queued-turn",
+ kind="message",
+ payload={"content": "queued"},
+ status=COMMAND_PENDING,
+ )
+ )
+ db.commit()
+ finally:
+ db.close()
+ before = _content_counts(task_id)
+
+ report = _redact([task_id])
+
+ assert report == TaskContentRedactionReport(busy=(task_id,))
+ assert _content_counts(task_id) == before
+ db = _direct_db_session()
+ try:
+ assert (
+ db.query(Task.title).filter(Task.id == task_id).scalar()
+ == (CONTENT_COLUMNS["title"])
+ )
+ finally:
+ db.close()
+
+
+def test_read_surfaces_answer_for_a_redacted_task(_roots: Path) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ _seed_content(task_id, _roots)
+ headers = _admin_headers()
+ # Warm the detail cache: the redaction pins ``updated_at``, the cache's
+ # freshness token, so only its invalidation keeps this from being served.
+ assert (
+ chat_client.get(f"/api/chat/task/{task_id}", headers=headers).json()["title"]
+ == (CONTENT_COLUMNS["title"])
+ )
+
+ _redact([task_id])
+
+ detail = chat_client.get(f"/api/chat/task/{task_id}", headers=headers)
+ assert detail.status_code == 200, detail.text
+ assert detail.json()["title"] == ""
+ assert detail.json()["dag_data"] is None
+ assert detail.json()["input_tokens"] == KEPT_COLUMNS["input_tokens"]
+ assert (
+ chat_client.get(f"/api/chat/task/{task_id}/status", headers=headers).status_code
+ == 200
+ )
+ listed = chat_client.get("/api/chat/tasks", headers=headers)
+ assert listed.status_code == 200, listed.text
+
+ v1_task = client.get(f"/v1/chat/tasks/{task_id}", headers=_bearer(full_key))
+ assert v1_task.status_code == 200, v1_task.text
+ assert v1_task.json()["output"] is None
+ steps = client.get(f"/v1/chat/tasks/{task_id}/steps", headers=_bearer(full_key))
+ assert steps.status_code == 200, steps.text
+ assert steps.json()["steps"] == []
+ assert steps.json()["steps_expired"] is True
+ files = client.get(f"/v1/chat/tasks/{task_id}/files", headers=_bearer(full_key))
+ assert files.status_code == 200, files.text
+ assert files.json()["files"] == []
+
+ log = client.get(f"/api/conversation-logs/{task_id}", headers=headers)
+ assert log.status_code == 200, log.text
+ assert log.json()["log"]["title"] == ""
+
+
+def test_files_only_deletion_removes_files_and_keeps_the_conversation(
+ _roots: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent_id, full_key = _create_agent_with_key()
+ task_id = _settled_task(full_key, agent_id)
+ busy_id = _settled_task(full_key, agent_id)
+ storage_key, local, workspace = _seed_content(task_id, _roots)
+ kb_local = _add_file(task_id, _roots, "kb-source")
+ _seed_content(busy_id, _roots)
+ deleted_id, kb_file_id = _file_ids(task_id)
+ monkeypatch.setattr(
+ task_deletion,
+ "find_referenced_file_ids",
+ lambda file_ids: {kb_file_id} & set(file_ids),
+ )
+ db = _direct_db_session()
+ try:
+ owner_id = int(db.query(Task.user_id).filter(Task.id == task_id).one()[0])
+ db.query(Task).filter(Task.id == busy_id).update({"status": TaskStatus.PAUSED})
+ db.commit()
+ finally:
+ db.close()
+ before = _content_counts(task_id)
+
+ db = _direct_db_session()
+ try:
+ first = delete_task_content_files(db, [task_id, busy_id, 9_000_001])
+ second = delete_task_content_files(db, [task_id])
+ finally:
+ db.close()
+
+ assert first == TaskFileDeletionReport(
+ deleted=(task_id,), busy=(busy_id,), missing=(9_000_001,)
+ )
+ assert second == TaskFileDeletionReport(deleted=(task_id,))
+ assert _content_counts(task_id) == {
+ **before,
+ UploadedFile.__tablename__: 0,
+ }
+ assert not local.exists()
+ assert not _object_exists(owner_id, storage_key)
+ assert kb_local.exists()
+ assert workspace.exists()
+ db = _direct_db_session()
+ try:
+ assert db.get(UploadedFileCleanupFence, deleted_id) is not None
+ kept = db.query(UploadedFile).filter(UploadedFile.file_id == kb_file_id).one()
+ assert (kept.task_id, kept.detached_reason) == (None, "task_deleted")
+ task = db.query(Task).filter(Task.id == task_id).one()
+ assert task.title == CONTENT_COLUMNS["title"]
+ assert len(_file_ids(busy_id)) == 1
+ finally:
+ db.close()
diff --git a/tests/web/services/test_task_content_redaction_rows.py b/tests/web/services/test_task_content_redaction_rows.py
new file mode 100644
index 000000000..71d0dacef
--- /dev/null
+++ b/tests/web/services/test_task_content_redaction_rows.py
@@ -0,0 +1,453 @@
+"""Row-level redaction and purge on both SQLite and PostgreSQL.
+
+``redact_task_rows`` and ``purge_task_rows`` share their content-row delete,
+whose statement order exists for foreign keys and the active-interaction
+CHECK. Both are run here against both dialects with foreign keys enforced,
+starting from a task whose checkpoint pointer and active interaction both
+name its trace row -- the shape that order exists for.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from unittest.mock import patch
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy.orm import Session, sessionmaker
+
+from tests.web.services.task_database_shared import engine as engine_fixture
+from tests.web.services.task_interaction_schema_shared import make_row
+from xagent.web.models.agent import Agent
+from xagent.web.models.chat_message import TaskChatMessage
+from xagent.web.models.database import Base
+from xagent.web.models.mcp import MCPServer, UserMCPServer
+from xagent.web.models.task import (
+ DAGExecution,
+ Task,
+ TaskConnectorRuntimeContext,
+ TaskStatus,
+ TraceCheckpointBlob,
+ TraceEvent,
+ TraceMessageBlob,
+)
+from xagent.web.models.task_channel_delivery import TaskChannelDelivery
+from xagent.web.models.task_command import TaskExecutionCommand
+from xagent.web.models.task_execution_event import TaskExecutionEvent
+from xagent.web.models.task_interaction import TaskInteractionRequest
+from xagent.web.models.trigger import AgentTrigger, TriggerRun, TriggerRunStatus
+from xagent.web.models.uploaded_file import UploadedFile
+from xagent.web.models.user import User
+from xagent.web.models.user_channel import UserChannel
+from xagent.web.services import channel_delivery
+from xagent.web.services.connector_runtime import prepare_append_connector_runtime
+from xagent.web.services.task_command_transport import COMMAND_PENDING
+from xagent.web.services.task_deletion import purge_task_rows, redact_task_rows
+from xagent.web.services.task_file_lifecycle import lock_attachment_task
+from xagent.web.services.task_runtime import PROMPT_CONTEXT_AGENT_CONFIG_KEY
+
+engine = engine_fixture
+
+NOW = datetime(2026, 11, 1, 12, 0, 0, tzinfo=timezone.utc)
+UPDATED_AT = datetime(2026, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
+
+#: Routing and authorization keys survive; prompt context and the creator IP
+#: are content.
+AGENT_CONFIG = {
+ "auth_mode": "widget",
+ "guest_id": "guest-1",
+ PROMPT_CONTEXT_AGENT_CONFIG_KEY: {"text": "secret"},
+ "widget_client_ip": "203.0.113.7",
+}
+
+CONTENT_TABLES = (
+ TraceEvent,
+ TraceMessageBlob,
+ TraceCheckpointBlob,
+ DAGExecution,
+ TaskChatMessage,
+ TaskExecutionEvent,
+ TaskInteractionRequest,
+)
+
+
+def sessions(engine) -> sessionmaker[Session]:
+ """Sessions shaped like production's: ``autoflush=False``."""
+ Base.metadata.create_all(engine)
+ return sessionmaker(bind=engine, autoflush=False)
+
+
+def _seed(db: Session) -> tuple[int, int, int]:
+ """A completed task with content, an anchored active interaction, a file,
+ a trigger run and a channel delivery still owed.
+
+ Returns ``(task_id, owner_id, channel_id)``.
+ """
+ user = User(username="owner", password_hash="unused")
+ db.add(user)
+ db.flush()
+ agent = Agent(user_id=user.id, name="agent")
+ channel = UserChannel(
+ user_id=user.id, channel_type="slack", channel_name="ws", config={}
+ )
+ db.add_all([agent, channel])
+ db.flush()
+ task = Task(
+ user_id=user.id,
+ agent_id=agent.id,
+ title="secret",
+ input="secret",
+ output="secret",
+ status=TaskStatus.COMPLETED,
+ input_tokens=7,
+ output_tokens=3,
+ agent_config=AGENT_CONFIG,
+ )
+ db.add(task)
+ db.flush()
+ trigger = AgentTrigger(
+ user_id=user.id, agent_id=agent.id, type="scheduled", name="t", config={}
+ )
+ db.add(trigger)
+ db.flush()
+ command = TaskExecutionCommand(
+ task_id=task.id,
+ command_id="turn-1",
+ kind="message",
+ payload={"content": "secret", "channel": {"id": channel.id}},
+ status="completed",
+ )
+ trace = TraceEvent(
+ task_id=task.id,
+ event_id="evt-1",
+ event_type="agent_execution_checkpoint",
+ timestamp=NOW,
+ data={"content": "secret"},
+ )
+ db.add_all([command, trace])
+ db.flush()
+ db.add_all(
+ [
+ TraceMessageBlob(
+ task_id=task.id,
+ execution_id="exec",
+ message_hash="m",
+ message_data={},
+ message_bytes=2,
+ ),
+ TraceCheckpointBlob(
+ task_id=task.id,
+ execution_id="exec",
+ blob_kind="messages",
+ blob_hash="c",
+ blob_data={},
+ blob_bytes=2,
+ ),
+ DAGExecution(task_id=task.id),
+ TaskChatMessage(
+ task_id=task.id,
+ user_id=user.id,
+ role="user",
+ content="secret",
+ message_type="user_message",
+ ),
+ TaskExecutionEvent(
+ event_id="exec-event-1",
+ task_id=task.id,
+ sequence=1,
+ scope_id="root",
+ idempotency_key="k1",
+ kind="assistant_message",
+ payload_version=1,
+ payload={"content": "secret"},
+ occurred_at=NOW,
+ ),
+ TaskInteractionRequest(
+ **make_row(task_id=task.id, resume_trace_event_id=trace.id, db=db)
+ ),
+ # No durable key and a path outside the uploads root: the
+ # redaction deletes the row and has no bytes to touch.
+ UploadedFile(
+ user_id=user.id,
+ task_id=task.id,
+ filename="a.txt",
+ storage_path="/nonexistent/a.txt",
+ file_size=1,
+ ),
+ TriggerRun(
+ trigger_id=trigger.id,
+ task_id=task.id,
+ status=TriggerRunStatus.COMPLETED.value,
+ idempotency_key=f"run-{task.id}",
+ payload_snapshot={"text": "secret"},
+ ),
+ # A reply still owed to the channel. The delivery worker reads
+ # its destination out of the command payload the redaction
+ # blanks.
+ TaskChannelDelivery(
+ command_id=command.id, channel_id=channel.id, destination={}
+ ),
+ ]
+ )
+ db.execute(
+ sa.update(Task)
+ .where(Task.id == task.id)
+ .values(
+ last_checkpoint_event_id="evt-1",
+ last_checkpoint_trace_event_id=trace.id,
+ interaction_protocol_version=1,
+ updated_at=UPDATED_AT,
+ )
+ )
+ db.commit()
+ return int(task.id), int(user.id), int(channel.id)
+
+
+def _redact(sessions: sessionmaker[Session], task_id: int, now: datetime) -> None:
+ with sessions() as db:
+ task = lock_attachment_task(db, task_id, deleting=True)
+ assert task is not None
+ redact_task_rows(db, task, now=now)
+ db.commit()
+
+
+def _utc(value: datetime) -> datetime:
+ """A stored timestamp as an aware UTC value on either dialect.
+
+ SQLite hands back naive UTC; PostgreSQL an aware value in the session's
+ zone, which ``replace`` would mislabel rather than convert.
+ """
+ return (
+ value.replace(tzinfo=timezone.utc)
+ if value.tzinfo is None
+ else value.astimezone(timezone.utc)
+ )
+
+
+def _count(db: Session, model: type, task_id: int) -> int:
+ return int(
+ db.execute(
+ sa.select(sa.func.count())
+ .select_from(model)
+ .where(model.task_id == task_id) # type: ignore[attr-defined]
+ ).scalar_one()
+ )
+
+
+def test_redact_task_rows_keeps_the_task_and_removes_its_content(sessions) -> None:
+ with sessions() as db:
+ task_id, owner_id, _ = _seed(db)
+
+ _redact(sessions, task_id, NOW)
+ # Idempotency: a re-run removes nothing and keeps the first trace stamp.
+ _redact(sessions, task_id, NOW + timedelta(days=1))
+
+ with sessions() as db:
+ assert {
+ model.__tablename__: _count(db, model, task_id) for model in CONTENT_TABLES
+ } == {model.__tablename__: 0 for model in CONTENT_TABLES}
+ assert (
+ db.query(UploadedFile).filter(UploadedFile.user_id == owner_id).count() == 0
+ )
+ task = db.get(Task, task_id)
+ assert task is not None
+ assert (task.title, task.input, task.output) == ("", None, None)
+ assert (task.input_tokens, task.output_tokens) == (7, 3)
+ assert task.agent_config == {"auth_mode": "widget", "guest_id": "guest-1"}
+ assert _utc(task.updated_at) == UPDATED_AT
+ assert _utc(task.traces_expired_at) == NOW
+ [command] = db.query(TaskExecutionCommand).filter_by(task_id=task_id).all()
+ assert command.payload == {}
+ [run] = db.query(TriggerRun).filter_by(task_id=task_id).all()
+ assert run.payload_snapshot is None
+
+
+def test_redaction_discards_the_pending_channel_delivery(sessions) -> None:
+ """A blanked command's delivery must leave the delivery worker's queue.
+
+ ``channel_delivery._pending`` picks pending deliveries of settled
+ commands, and the claim then reads the channel out of the command
+ payload; with that payload blanked, a still-pending row would fail its
+ claim on every pass and starve the rest of the channel's queue.
+ """
+ with sessions() as db:
+ task_id, _, channel_id = _seed(db)
+ command_id = int(db.query(TaskChannelDelivery.command_id).one()[0])
+
+ with patch.object(channel_delivery, "get_session_local", return_value=sessions):
+ assert channel_delivery._pending(channel_id) == [command_id]
+ _redact(sessions, task_id, NOW)
+ assert channel_delivery._pending(channel_id) == []
+
+ with sessions() as db:
+ [delivery] = db.query(TaskChannelDelivery).all()
+ assert (delivery.status, delivery.claim_token) == ("discarded", None)
+
+
[email protected]("lease_live", [True, False])
+def test_a_claimed_delivery_is_left_to_its_sender_while_the_lease_is_live(
+ sessions, lease_live: bool
+) -> None:
+ """A sender holding a live claim already read the reply and settles it;
+ an expired claim would be re-claimed against the blanked payload."""
+ with sessions() as db:
+ task_id, _, _ = _seed(db)
+ db.query(TaskChannelDelivery).update(
+ {
+ "claim_token": "sender",
+ "available_at": NOW + timedelta(minutes=1 if lease_live else -1),
+ }
+ )
+ db.commit()
+
+ _redact(sessions, task_id, NOW)
+
+ with sessions() as db:
+ [delivery] = db.query(TaskChannelDelivery).all()
+ assert (delivery.status, delivery.claim_token) == (
+ ("pending", "sender") if lease_live else ("discarded", None)
+ )
+
+
+def test_a_command_still_owed_execution_keeps_its_payload(sessions) -> None:
+ """On SQLite the quiescence check and the redaction are not atomic, so a
+ command can be enqueued in between; it must not run with ``{}``."""
+ with sessions() as db:
+ task_id, _, _ = _seed(db)
+ db.add(
+ TaskExecutionCommand(
+ task_id=task_id,
+ command_id="queued",
+ kind="message",
+ payload={"content": "queued"},
+ status=COMMAND_PENDING,
+ )
+ )
+ db.commit()
+
+ _redact(sessions, task_id, NOW)
+
+ with sessions() as db:
+ payloads = {
+ command.command_id: command.payload
+ for command in db.query(TaskExecutionCommand).filter_by(task_id=task_id)
+ }
+ assert payloads == {"turn-1": {}, "queued": {"content": "queued"}}
+
+
+def test_a_task_without_a_trace_keeps_traces_expired_at_null(sessions) -> None:
+ with sessions() as db:
+ user = User(username="traceless", password_hash="unused")
+ db.add(user)
+ db.flush()
+ task = Task(user_id=user.id, title="secret", status=TaskStatus.COMPLETED)
+ db.add(task)
+ db.commit()
+ task_id = int(task.id)
+
+ _redact(sessions, task_id, NOW)
+
+ with sessions() as db:
+ task = db.get(Task, task_id)
+ assert task is not None
+ assert (task.title, task.traces_expired_at) == ("", None)
+
+
+def test_purge_task_rows_still_deletes_the_task_and_detaches_files(sessions) -> None:
+ with sessions() as db:
+ task_id, owner_id, _ = _seed(db)
+
+ with sessions() as db:
+ assert purge_task_rows(db, task_id=task_id, detached_reason="task_deleted")
+ db.commit()
+
+ with sessions() as db:
+ assert db.get(Task, task_id) is None
+ assert all(_count(db, model, task_id) == 0 for model in CONTENT_TABLES)
+ [file] = db.query(UploadedFile).filter(UploadedFile.user_id == owner_id).all()
+ assert (file.task_id, file.detached_reason) == (None, "task_deleted")
+
+
+def test_a_redacted_connector_bound_task_can_take_another_turn(sessions) -> None:
+ """The connector runtime context survives: the next turn is checked
+ against it, and without it a required context key could never be
+ satisfied again (resending it is refused as a change)."""
+ with sessions() as db:
+ owner = User(username="connector-owner", password_hash="unused")
+ db.add(owner)
+ db.flush()
+ server = MCPServer(
+ name="runtime",
+ description="runtime",
+ managed="external",
+ transport="streamable_http",
+ url="https://example.com/mcp",
+ runtime_input_schema={
+ "context": {"account_id": {"type": "string", "required": True}}
+ },
+ runtime_bindings=[
+ {
+ "source": {"input_type": "context", "key": "account_id"},
+ "target": {"target_type": "mcp_meta", "key": "account_id"},
+ }
+ ],
+ )
+ agent = Agent(
+ user_id=owner.id,
+ name="connector agent",
+ instructions="Use tools.",
+ tool_categories=["mcp"],
+ )
+ db.add_all([server, agent])
+ db.flush()
+ db.add(
+ UserMCPServer(
+ user_id=owner.id,
+ mcpserver_id=server.id,
+ is_owner=True,
+ can_edit=True,
+ can_delete=True,
+ is_active=True,
+ )
+ )
+ ref = {"connector_type": "mcp", "connector_id": int(server.id)}
+ task = Task(
+ user_id=owner.id,
+ agent_id=agent.id,
+ title="secret",
+ source="sdk",
+ status=TaskStatus.COMPLETED,
+ connector_runtime_selected_refs=[ref],
+ )
+ db.add(task)
+ db.flush()
+ db.add(
+ TaskConnectorRuntimeContext(
+ task_id=task.id,
+ connector_type="mcp",
+ connector_id=server.id,
+ context={"account_id": "acct-1"},
+ )
+ )
+ db.commit()
+ task_id, owner_id, agent_id = int(task.id), int(owner.id), int(agent.id)
+
+ _redact(sessions, task_id, NOW)
+
+ with sessions() as db:
+ task = db.get(Task, task_id)
+ agent = db.get(Agent, agent_id)
+ assert task is not None and agent is not None
+ for payload_items in (
+ None,
+ [{"connector_ref": ref, "context": {"account_id": "acct-1"}}],
+ ):
+ plan = prepare_append_connector_runtime(
+ db=db,
+ agent=agent,
+ task=task,
+ connector_user_id=owner_id,
+ payload_items=payload_items,
+ )
+ assert plan.ephemeral_by_ref == {}