test_state.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import time
  2. from data_query_agent.state import StateStore
  3. def test_conversations_are_isolated_and_resettable(tmp_path) -> None:
  4. store = StateStore(tmp_path / "state.sqlite3", idle_hours=24)
  5. first = store.get_conversation("group:c1:u1")
  6. second = store.get_conversation("group:c2:u1")
  7. assert first.session_id != second.session_id
  8. store.set_thread(first.key, "thread-1")
  9. assert store.get_conversation(first.key).thread_id == "thread-1"
  10. cleared = store.reset_conversation(first.key, new_session=False)
  11. assert cleared.session_id == first.session_id
  12. assert cleared.thread_id is None
  13. renewed = store.reset_conversation(first.key, new_session=True)
  14. assert renewed.session_id != first.session_id
  15. def test_message_claim_is_idempotent(tmp_path) -> None:
  16. store = StateStore(tmp_path / "state.sqlite3")
  17. assert store.claim_message("m1", "p2p:c1:u1") is True
  18. assert store.claim_message("m1", "p2p:c1:u1") is False
  19. def test_active_run_is_failed_without_overwriting_completed_run(tmp_path) -> None:
  20. store = StateStore(tmp_path / "state.sqlite3")
  21. active_dir = tmp_path / "active"
  22. done_dir = tmp_path / "done"
  23. store.create_run("r1", "p2p:c1:u1", "m1", active_dir)
  24. store.create_run("r2", "p2p:c1:u1", "m1", done_dir)
  25. store.update_run("r2", "completed")
  26. store.fail_active_runs("m1", "safe error")
  27. rows = store._conn.execute("SELECT run_id, status FROM runs ORDER BY run_id").fetchall()
  28. assert [(row["run_id"], row["status"]) for row in rows] == [
  29. ("r1", "failed"),
  30. ("r2", "completed"),
  31. ]
  32. def test_idle_conversation_starts_new_thread(tmp_path) -> None:
  33. store = StateStore(tmp_path / "state.sqlite3", idle_hours=1)
  34. conversation = store.get_conversation("p2p:c1:u1")
  35. store.set_thread(conversation.key, "old-thread")
  36. with store._conn:
  37. store._conn.execute(
  38. "UPDATE conversations SET last_active_at=? WHERE conversation_key=?",
  39. (time.time() - 7200, conversation.key),
  40. )
  41. expired = store.get_conversation(conversation.key)
  42. assert expired.thread_id is None
  43. assert expired.session_id != conversation.session_id