Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions openviking/session/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from openviking.message.part import ContextPart, TextPart, ToolPart
from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotFoundError
from openviking.server.config import ToolOutputExternalizationConfig
from openviking.server.error_mapping import map_exception
from openviking.server.identity import RequestContext, Role
from openviking.session.auto_commit_policy import AutoCommitPolicy
from openviking.session.extraction_batch import (
Expand Down Expand Up @@ -60,6 +61,7 @@
from openviking.utils.token_estimation import estimate_text_tokens, truncate_text_to_token_budget
from openviking_cli.exceptions import (
FailedPreconditionError,
InternalError,
NotFoundError,
)
from openviking_cli.session.user_id import UserIdentifier
Expand Down Expand Up @@ -2170,15 +2172,6 @@ async def commit_async(
queue_msg.to_dict(),
)

phase1_stage = "task_tracker_create"
await get_task_tracker().create(
"session_commit",
resource_id=self.session_id,
account_id=self.ctx.account_id,
user_id=self.ctx.user.user_id,
task_id=task_id,
)

phase1_stage = "phase1_persist"
self._messages = retained_messages
await self._write_to_agfs_async(messages=self._messages)
Expand Down Expand Up @@ -2232,6 +2225,25 @@ async def commit_async(
self._compression.original_count += len(messages_to_archive)
logger.info(f"Archived: {len(messages_to_archive)} messages → {archive_uri}/")

# Registration must not hold the session lock or roll back published Phase 1.
try:
await get_task_tracker().create(
"session_commit",
resource_id=self.session_id,
account_id=self.ctx.account_id,
user_id=self.ctx.user.user_id,
task_id=task_id,
)
except Exception as exc:
error = map_exception(exc) or InternalError(str(exc))
error.details.update(
task_id=task_id,
archive_uri=archive_uri,
archived=True,
stage="task_tracker_create",
)
raise error

return {
"session_id": self.session_id,
"status": "accepted",
Expand Down
15 changes: 8 additions & 7 deletions openviking/storage/queuefs/session_commit_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,6 @@ async def _process(self, msg: SessionCommitMsg, ctx: RequestContext) -> bool:
if not await session.exists():
error = f"Session '{msg.session_id}' no longer exists"
tracker = get_task_tracker()
await tracker.create(
"session_commit",
resource_id=msg.session_id,
account_id=ctx.account_id,
user_id=ctx.user.user_id,
task_id=msg.task_id,
)
await tracker.fail(
msg.task_id,
error,
Expand Down Expand Up @@ -124,6 +117,14 @@ async def on_dequeue(self, data: Optional[Dict[str, Any]]) -> Optional[Dict[str,
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
self.report_error(str(exc), data)
return None
# Failed registration must retain queue work; processing errors remain terminal.
await get_task_tracker().create(
"session_commit",
resource_id=msg.session_id,
account_id=ctx.account_id,
user_id=ctx.user.user_id,
task_id=msg.task_id,
)
try:
await self._process(msg, ctx)
except Exception as exc:
Expand Down
61 changes: 31 additions & 30 deletions tests/session/test_session_retention_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@

from openviking.message import Message, TextPart, ToolPart
from openviking.models.vlm.base import ToolCall, VLMResponse
from openviking.service.task_tracker import get_task_tracker
from openviking.pyagfs.exceptions import AGFSIoError
from openviking.service.task_store import PersistentTaskStore
from openviking.service.task_tracker import TaskTracker, get_task_tracker
from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPES
from openviking.session.session import Session, _ArchiveSummaryResult, _CheckpointRequest
from openviking.storage.viking_fs import VikingFS
from openviking_cli.exceptions import UnavailableError
from tests.utils.mock_agfs import MockLocalAGFS


async def _write_archive(
Expand Down Expand Up @@ -1797,41 +1802,37 @@ async def write_then_fail(messages, *, lease_ref=None):
assert [message["parts"][0]["text"] for message in context["messages"]] == ["retained tail"]


async def test_phase1_enqueues_before_root_rewrite_and_publishes_ready_last(
client,
monkeypatch,
):
session = client(session_id="phase1_publish_order_test")
async def test_phase1_publishes_and_unlocks_before_task_registration(tmp_path, monkeypatch):
fs = VikingFS(agfs=MockLocalAGFS(root_path=tmp_path))
tracker = TaskTracker(PersistentTaskStore(fs.agfs))
monkeypatch.setattr("openviking.service.task_tracker.get_task_tracker", lambda: tracker)
monkeypatch.setattr("openviking.session.session._enabled_memory_types", lambda: set())
session = Session(viking_fs=fs, session_id="phase1_publish_order_test")
await session.ensure_exists()
session.add_message("user", [TextPart("archive me")])
observations: list[tuple[list[str], str]] = []
await session.add_message_async("user", [TextPart("archive me")])

class InspectingQueueManager:
async def enqueue(self, _queue_name, data):
root = await session._read_live_messages_strict()
archive_uri = data["archive_uri"]
observations.append(
(
[message.content for message in root],
(await session._read_phase1_meta(archive_uri)).get("status", ""),
)
)
async def enqueue(_queue_name, data):
assert len(await session._read_live_messages_strict()) == 1
assert (await session._read_phase1_meta(data["archive_uri"]))["status"] == "preparing"

async def create_task(task):
lease = await fs._async_agfs.pathlock_acquire_tree(
fs._uri_to_path(session.uri, ctx=session.ctx)
)
await fs._async_agfs.pathlock_release(lease)
raise AGFSIoError("task store unavailable")

monkeypatch.setattr(tracker._store, "create", create_task)
monkeypatch.setattr(
"openviking.storage.queuefs.get_queue_manager",
lambda: InspectingQueueManager(),
"openviking.storage.queuefs.get_queue_manager", lambda: SimpleNamespace(enqueue=enqueue)
)

result = await session.commit_async()
session.add_message("user", [TextPart("wait for predecessor")])
second = await session.commit_async()
assert observations == [
(["archive me"], "preparing"),
(["wait for predecessor"], "preparing"),
]
assert (await session._read_phase1_meta(result["archive_uri"]))["status"] == "ready"
assert (await session._read_phase1_meta(second["archive_uri"]))["status"] == "ready"
with pytest.raises(UnavailableError, match="task store unavailable") as error:
await session.commit_async()
archive_uri = error.value.details["archive_uri"]
assert error.value.details["archived"] is True
assert (await session._read_phase1_meta(archive_uri))["status"] == "ready"
assert await session._read_live_messages_strict() == []
assert not await fs.exists(f"{archive_uri}/.failed.json", ctx=session.ctx)


async def test_interrupted_phase1_recovers_when_root_rewrite_is_durable(
Expand Down
29 changes: 14 additions & 15 deletions tests/test_task_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,35 +237,32 @@ async def test_task_result_redacts_user_key(tracker: TaskTracker):
assert "user_key" not in json.dumps(retrieved.to_dict())


async def test_fail_task(tracker: TaskTracker):
async def test_fail_task(tracker: TaskTracker, monkeypatch):
"""A Phase-2 load failure must persist failure before acknowledging its queue work."""
from types import SimpleNamespace
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, Mock

from openviking.service.task_work_index import TaskWorkIndex
from openviking.storage.queuefs.named_queue import NamedQueue
from openviking.storage.queuefs.session_commit_msg import SessionCommitMsg
from openviking.storage.queuefs.session_commit_processor import SessionCommitProcessor

task = await tracker.create("session_commit", resource_id="session-1", **_owner_kwargs())
index = TaskWorkIndex()
tracker.attach_work_index(index)
set_task_tracker(tracker)
task_id = "session-commit-1"
backend = _FakeAgfs()
session = SimpleNamespace(
exists=AsyncMock(return_value=True),
load=AsyncMock(side_effect=json.JSONDecodeError("torn session message", "{", 1)),
)
processor = SessionCommitProcessor(SimpleNamespace(session=Mock(return_value=session)))
queue = NamedQueue(
backend,
"/queue",
"SessionCommit",
dequeue_handler=SessionCommitProcessor(
SimpleNamespace(session=lambda *args, **kwargs: session)
),
task_work_index=index,
dequeue_handler=processor,
task_work_index=tracker._work_index,
)
msg = SessionCommitMsg(
task_id=task.task_id,
task_id=task_id,
session_id="session-1",
session_uri="viking://user/alice/sessions/session-1",
archive_uri="viking://user/alice/sessions/session-1/history/archive_001",
Expand All @@ -277,15 +274,17 @@ async def test_fail_task(tracker: TaskTracker):
{"id": "delivery-1", "data": payload}
).encode()

with monkeypatch.context() as patch:
patch.setattr(tracker._store, "create", AsyncMock(side_effect=OSError("store unavailable")))
await queue.dequeue()
assert f"{queue.path}/ack" not in backend.files

await queue.dequeue()

retrieved = await tracker.get(task.task_id)
persisted = await tracker._store.get(task.task_id, **_owner_kwargs())
assert retrieved.status == TaskStatus.FAILED
persisted = await tracker._store.get(task_id, **_owner_kwargs())
assert persisted["status"] == "failed"
assert "torn session message" in persisted["error"]
assert backend.files[f"{queue.path}/ack"] == b"delivery-1"
assert not index.has_work(task.task_id)


async def test_mark_externally_cancelled_task_without_enabling_active_cancel(
Expand Down