mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 07:31:42 +08:00
Closes #2909. Omit the fewest eligible historical tool-argument payloads so oversized completed exchanges remain replayable, without touching signed/native provider rounds or durable history.
228 lines
10 KiB
Python
228 lines
10 KiB
Python
"""A whole exchange must fit the returned history plan without corrupting replay."""
|
|
|
|
from copy import deepcopy
|
|
import json
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from deeptutor.core.stream import StreamEventType
|
|
from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider
|
|
from deeptutor.services.session.context_builder import ContextBuilder, HistoryBudgetExceeded
|
|
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
|
|
from tests.services.session.test_model_history import turn_record
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("summarizes", [False, True])
|
|
@pytest.mark.parametrize("recorded", [False, True])
|
|
@pytest.mark.parametrize("prior_summary", [False, True])
|
|
async def test_oversized_last_exchange_is_rejected_without_changing_durable_history(
|
|
tmp_path, monkeypatch, summarizes, recorded, prior_summary
|
|
):
|
|
monkeypatch.setenv("DEEPTUTOR_CHAT_ENGINE", "python")
|
|
store = SQLiteSessionStore(tmp_path / "history.db")
|
|
sid = (await store.create_session())["id"]
|
|
for role, content in [
|
|
("user", "Earlier question"),
|
|
("assistant", "Earlier answer"),
|
|
("user", "Latest question"),
|
|
]:
|
|
await store.add_message(sid, role, content)
|
|
metadata = {"model_turn": turn_record("alpha " * 3000)} if recorded else None
|
|
await store.add_message(
|
|
sid, "assistant", "Display answer" if recorded else "alpha " * 3000, metadata=metadata
|
|
)
|
|
before = deepcopy(await store.get_messages_for_context(sid))
|
|
watermark = before[1]["id"] if prior_summary else 0
|
|
if prior_summary:
|
|
await store.update_summary(sid, "Previous valid summary", watermark)
|
|
builder = ContextBuilder(store)
|
|
monkeypatch.setattr(builder, "_history_budget", lambda config: 1024)
|
|
summary = (
|
|
AsyncMock(return_value=("Small successful summary", []))
|
|
if summarizes
|
|
else AsyncMock(side_effect=ValueError("synthetic failure"))
|
|
)
|
|
config = SimpleNamespace(
|
|
model="gpt-test", binding="openai", context_window=1048576, max_tokens=4096
|
|
)
|
|
with patch.object(builder, "_summarize", summary):
|
|
with pytest.raises(ValueError, match="history.*budget") as raised:
|
|
await builder.build(session_id=sid, llm_config=config)
|
|
assert raised.value.error_code == "history_budget_exceeded"
|
|
assert raised.value.retryable is False
|
|
assert raised.value.token_count > raised.value.budget == 1024
|
|
assert await store.get_messages_for_context(sid) == before
|
|
state = await store.get_session(sid)
|
|
assert (state.get("summary_up_to_msg_id") or 0) < before[-1]["id"]
|
|
if not summarizes:
|
|
assert (state.get("summary_up_to_msg_id") or 0) == watermark
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_whole_small_tool_exchange_remains_replayable(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("DEEPTUTOR_CHAT_ENGINE", "python")
|
|
store = SQLiteSessionStore(tmp_path / "history.db")
|
|
sid = (await store.create_session())["id"]
|
|
await store.add_message(sid, "user", "Question")
|
|
record = turn_record("Short evidence")
|
|
await store.add_message(sid, "assistant", "Display answer", metadata={"model_turn": record})
|
|
config = SimpleNamespace(
|
|
model="gpt-test", binding="openai", context_window=1048576, max_tokens=4096
|
|
)
|
|
result = await ContextBuilder(store).build(session_id=sid, llm_config=config)
|
|
assert result.token_count <= result.budget
|
|
assert result.model_history == record["messages"]
|
|
|
|
|
|
async def _oversized_tool_history(tmp_path, monkeypatch, record):
|
|
monkeypatch.setenv("DEEPTUTOR_CHAT_ENGINE", "python")
|
|
store = SQLiteSessionStore(tmp_path / "history.db")
|
|
sid = (await store.create_session())["id"]
|
|
await store.add_message(sid, "user", "Question")
|
|
await store.add_message(sid, "assistant", "Display answer", metadata={"model_turn": record})
|
|
builder = ContextBuilder(store)
|
|
monkeypatch.setattr(builder, "_history_budget", lambda config: 1024)
|
|
monkeypatch.setattr(builder, "_summarize", AsyncMock(side_effect=ValueError("fixture")))
|
|
config = SimpleNamespace(
|
|
binding=record["route"]["provider"],
|
|
model=record["route"]["model"],
|
|
context_window=4096,
|
|
max_tokens=512,
|
|
)
|
|
return builder, sid, config
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("backup", ["identical", "different", "absent"])
|
|
async def test_oversized_completed_tool_call_can_be_replayed(tmp_path, monkeypatch, backup):
|
|
record = turn_record()
|
|
record["route"] = {"provider": "custom", "model": "vendor/deepseek-test"}
|
|
question, assistant, evidence, answer = record["messages"]
|
|
assistant["tool_calls"][0]["function"]["arguments"] = json.dumps({"key": "payload " * 3000})
|
|
reasoning = "plan " * 650 if backup == "identical" else "original reasoning"
|
|
assistant["reasoning_content"] = reasoning
|
|
if backup != "absent":
|
|
assistant["_provider_response_state"] = {
|
|
"reasoning_content": reasoning if backup == "identical" else "distinct provider state"
|
|
}
|
|
builder, sid, config = await _oversized_tool_history(tmp_path, monkeypatch, record)
|
|
before = await builder.store.get_messages_for_context(sid)
|
|
on_event = AsyncMock()
|
|
|
|
result = await builder.build(session_id=sid, llm_config=config, on_event=on_event)
|
|
|
|
replay_question, replay_call, replay_result, replay_answer = result.model_history
|
|
assert (replay_question, replay_result, replay_answer) == (question, evidence, answer)
|
|
call = replay_call["tool_calls"][0]
|
|
assert call["id"] == replay_result["tool_call_id"]
|
|
assert (call["type"], call["function"]["name"]) == ("function", "lookup")
|
|
arguments = call["function"]["arguments"]
|
|
assert isinstance(json.loads(arguments), dict)
|
|
assert len(arguments) < len(assistant["tool_calls"][0]["function"]["arguments"])
|
|
assert replay_call.get("_provider_response_state") == assistant.get("_provider_response_state")
|
|
wire = OpenAICompatProvider._sanitize_messages(result.model_history)
|
|
assert wire[1]["reasoning_content"] == reasoning
|
|
assert wire[1]["tool_calls"][0]["id"] == wire[2]["tool_call_id"]
|
|
assert result.token_count <= result.budget == 1024
|
|
assert any(event.type == StreamEventType.PROGRESS for event in result.events)
|
|
assert [call.args[0] for call in on_event.await_args_list] == result.events
|
|
assert await builder.store.get_messages_for_context(sid) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_only_oversized_tool_arguments_are_omitted(tmp_path, monkeypatch):
|
|
record = turn_record()
|
|
assistant = record["messages"][1]
|
|
short_call = assistant["tool_calls"][0]
|
|
query = (
|
|
"Find the example proving the theorem about right triangles, with its diagram "
|
|
"and the definition of the two angles used in the proof."
|
|
)
|
|
short_call["function"]["arguments"] = json.dumps({"key": query})
|
|
long_call = deepcopy(short_call)
|
|
long_call["id"] = "call-2"
|
|
long_call["function"]["arguments"] = json.dumps({"key": "detailed notes " * 3000})
|
|
assistant["tool_calls"].append(long_call)
|
|
record["messages"].insert(3, {"role": "tool", "tool_call_id": "call-2", "content": "Notes"})
|
|
builder, sid, config = await _oversized_tool_history(tmp_path, monkeypatch, record)
|
|
|
|
result = await builder.build(session_id=sid, llm_config=config)
|
|
|
|
replay_short, replay_long = result.model_history[1]["tool_calls"]
|
|
assert replay_short == short_call
|
|
assert replay_long["id"] == long_call["id"]
|
|
assert replay_long["function"]["arguments"] != long_call["function"]["arguments"]
|
|
assert result.model_history[2:] == record["messages"][2:]
|
|
assert result.token_count <= result.budget
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_duplicate_reasoning_alone_does_not_shorten_tool_arguments(tmp_path, monkeypatch):
|
|
record = turn_record()
|
|
assistant = record["messages"][1]
|
|
assistant["reasoning_content"] = "plan " * 650
|
|
assistant["_provider_response_state"] = {"reasoning_content": assistant["reasoning_content"]}
|
|
builder, sid, config = await _oversized_tool_history(tmp_path, monkeypatch, record)
|
|
on_event = AsyncMock()
|
|
|
|
result = await builder.build(session_id=sid, llm_config=config, on_event=on_event)
|
|
|
|
assert result.token_count <= result.budget
|
|
assert result.model_history == record["messages"]
|
|
assert OpenAICompatProvider._sanitize_messages(result.model_history) == (
|
|
OpenAICompatProvider._sanitize_messages(record["messages"])
|
|
)
|
|
assert result.events == []
|
|
on_event.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("protocol", ["gemini", "responses"])
|
|
async def test_signed_or_native_tool_calls_still_enforce_the_history_budget(
|
|
tmp_path, monkeypatch, protocol
|
|
):
|
|
record = turn_record()
|
|
assistant = record["messages"][1]
|
|
call = assistant["tool_calls"][0]
|
|
call["function"]["arguments"] = json.dumps({"key": "payload " * 3000})
|
|
if protocol == "gemini":
|
|
record["route"] = {"provider": "gemini", "model": "gemini-test"}
|
|
call["extra_content"] = {"google": {"thought_signature": "opaque-signature"}}
|
|
else:
|
|
assistant["_provider_response_state"] = {
|
|
"responses_output_items": [
|
|
{"type": "reasoning", "id": "r", "encrypted_content": "opaque"}
|
|
]
|
|
}
|
|
builder, sid, config = await _oversized_tool_history(tmp_path, monkeypatch, record)
|
|
before = await builder.store.get_messages_for_context(sid)
|
|
|
|
with pytest.raises(HistoryBudgetExceeded):
|
|
await builder.build(session_id=sid, llm_config=config)
|
|
|
|
assert await builder.store.get_messages_for_context(sid) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_large_window_does_not_bypass_the_real_history_plan(tmp_path, monkeypatch):
|
|
from deeptutor.services.session.context_builder import MAX_HISTORY_PLAN_TOKENS
|
|
|
|
monkeypatch.setenv("DEEPTUTOR_CHAT_ENGINE", "python")
|
|
store = SQLiteSessionStore(tmp_path / "history.db")
|
|
sid = (await store.create_session())["id"]
|
|
await store.add_message(sid, "user", "Previous question")
|
|
await store.add_message(sid, "assistant", "alpha " * 150000)
|
|
builder = ContextBuilder(store)
|
|
config = SimpleNamespace(
|
|
model="gpt-test", binding="openai", context_window=1048576, max_tokens=4096
|
|
)
|
|
with patch.object(builder, "_summarize", AsyncMock(side_effect=ValueError("fixture"))):
|
|
with pytest.raises(HistoryBudgetExceeded) as raised:
|
|
await builder.build(session_id=sid, llm_config=config)
|
|
assert raised.value.budget == MAX_HISTORY_PLAN_TOKENS
|
|
assert raised.value.token_count > MAX_HISTORY_PLAN_TOKENS
|
|
assert "alpha" not in str(raised.value)
|